Code Monkey home page Code Monkey logo

golang-interview's Introduction

Вопросы для собеседования по Go

ℹ️ В этом репозитории содержаться вопросы и ответы с помощью которых вы можете подготовиться к собеседованию по Golang

📱 Telegram-канал - @golangquiz

📊 Вопросов - 14.

📝 Вы можете добавить свой вопрос или обьяснение, исправить/дополнить существующий с помощью пул реквеста :)

Todo:

  • разделить вопросы по категориям
  • разделить вопросы по сложности

Список вопросов и ответов

1. Какие основные фичи GO?
  • Сильная статическая типизация - тип переменных не может быть изменен с течением времени, и они должны быть определены во время компиляции
  • Быстрое время компиляции
  • Встроенная конкурентность
  • Встроеный сборщик мусора
  • Компилируется в один бинарник - все, что вам нужно для запуска приложения. Очень полезно для управления версиями во время выполнения.
2. Что выведет код?
package main
 
import (
	"fmt"
	"sync"
	"time"
)
 
func main() {
	var wg sync.WaitGroup
	
	wg.Add(1)
	go func() {
		time.Sleep(time.Second * 2)
		fmt.Println("1")
		wg.Done()
	}()

	go func() {
		fmt.Println("2")
	}()

	wg.Wait()
	fmt.Println("3")
}
Ответ
всегда 2 1 3
3. Что выведет код?
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	timeout := 3 * time.Second
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	select {
	case <-time.After(1 * time.Second):
		fmt.Println("waited for 1 sec")
	case <-time.After(2 * time.Second):
		fmt.Println("waited for 2 sec")
	case <-time.After(3 * time.Second):
		fmt.Println("waited for 3 sec")
	case <-ctx.Done():
		fmt.Println(ctx.Err())
	}
}
Ответ
waited for 1 sec
4. Что выведет код?
package main

import (
	"container/heap"
	"fmt"
)

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func main() {
	h := &IntHeap{2, 1, 5}
	heap.Init(h)
	fmt.Printf("first: %d\n", (*h)[0])
}
Ответ
first: 1
5. Что выведет код?
package main

import (
	"fmt"
)

func mod(a []int) {
	// Как и почему изменится вывод если раскомментировать строку ниже?
	// a = append(a, 125)
	
	for i := range a {
		a[i] = 5
	}
	
	fmt.Println(a)
}

func main() {
	sl := []int{1, 2, 3, 4}
	mod(sl)
	fmt.Println(sl)
}
Ответ
[5 5 5 5]
[5 5 5 5]
если раскомментировать `a = append(a, 125)`
[5 5 5 5 5]
[1 2 3 4]
6. Что выведет код? (тема - defer)
package main

import (
	"fmt"
)

func main() {
	i := 0
	defer fmt.Println(i)
	i++
	return
}
Ответ
0
7. Что выведет код? (тема - defer)
package main

import (
	"fmt"
)

func main() {
	for i := 0; i < 5; i++ {
		defer func(i *int) {
			fmt.Printf("%v ", *i)
		}(&i)
	}

}
Ответ
5 5 5 5 5
8. Предположим, что x объявлен, а y не объявлен, какие пункты ниже верны?
x, _ := f()
x, _ = f()
x, y := f()
x, y = f()
Ответ
x, _ = f()
x, y := f()
9. Что делает runtime.newobject()?

Выделяет память в куче. https://golang.org/pkg/runtime/?m=all#newobject

10. Что такое $GOROOT и $GOPATH?

$GOROOT каталог для стандартной библиотеки, включая исполняемые файлы и исходный код.
$GOPATH каталго для внешних пакетов.

11. Что выведет код? (тема - slice)
package main

import (
	"fmt"
)

func main() {
	test1 := []int{1, 2, 3, 4, 5}
	test1 = test1[:3]
	test2 := test1[3:]
	fmt.Println(test2[:2])
}
Ответ
[4 5]
12. Перечислите функции которые могу остановить выполнение текущей горутины

runtime.Gosched
runtime.gopark
runtime.notesleep
runtime.Goexit

13. Что выведет код?
x := []int{1, 2}
y := []int{3, 4}
ref := x
x = y
fmt.Println(x, y, ref)
Ответ
[3 4] [3 4] [1 2]
14. Как скопировать slice?

Следует воспользоваться встроенной функцией copy:

x := []int{1, 2}
y := []int{3, 4}
ref := x
copy(x, y)
fmt.Println(x, y, ref)
// Output: [3 4] [3 4] [3 4]

golang-interview's People

Contributors

vallerion avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.