- vừa được xem lúc

80 COMMON GOLANG INTERVIEW QUESTIONS

0 0 3

Người đăng: Truong Phung

Theo Viblo Asia

80 Common Golang Interview Questions and Answers

1. What is Golang?

Go, or Golang, is an open-source programming language developed by Google. It is statically typed, compiled, and designed for building scalable and high-performance applications.

2. What are the key features of Go?

  • Concurrency support using Goroutines.
  • Garbage collection.
  • Statically typed with dynamic behavior.
  • Simple syntax.
  • Fast compilation.

3. What are Goroutines?

Goroutines are lightweight threads managed by the Go runtime. They are functions or methods that run concurrently with other functions or methods.

4. How do you create a Goroutine?

Use the go keyword before a function call:

go myFunction()

5. What is a channel in Go?

Channels are a way for Goroutines to communicate with each other and synchronize their execution. They allow sending and receiving values.

6. How do you declare a channel?

ch := make(chan int)

7. What is a buffered channel?

A buffered channel has a specified capacity and allows sending of values until the buffer is full. It doesn't require a receiver to be ready to receive.

8. How do you close a channel?

Use the close() function:

close(ch)

9. What is a struct in Go?

A struct is a user-defined type that allows grouping fields of different data types into a single entity.

10. How do you define a struct?

type Person struct { Name string Age int
}

11. What is an interface in Go?

An interface in Go is a type that specifies a set of method signatures. It allows polymorphism by defining behavior.

12. How do you implement an interface?

A type implements an interface by implementing all its methods:

 type Animal interface { Speak() string } type Dog struct{} func (d Dog) Speak() string { return "Woof!" }

13. What is the defer keyword?

defer is used to postpone the execution of a function until the surrounding function returns.

14. How does defer work?

Deferred functions are executed in LIFO (Last In, First Out) order:

defer fmt.Println("world")
fmt.Println("hello")
// Output: hello world

15. What is a pointer in Go?

A pointer holds the memory address of a value. It is used to pass references instead of copying values.

16. How do you declare a pointer?

var p *int
p = &x

17. What is the difference between new and make?

  • new allocates memory but doesn't initialize the value.
  • make allocates and initializes memory for slices, maps, and channels.

18. What is a slice in Go?

A slice is a dynamically-sized array that provides a more flexible way to work with sequences of elements.

19. How do you create a slice?

s := make([]int, 0)

20. What is a map in Go?

A map is a collection of key-value pairs.

21. How do you create a map?

m := make(map[string]int)

22. What is the select statement?

select allows a Goroutine to wait on multiple communication operations.

23. How do you use select?

select { case msg := <-ch: fmt.Println(msg) default: fmt.Println("No message received") }

24. What is a nil channel?

A nil channel blocks both sending and receiving operations.

25. What is the init function?

init is a special function that initializes package-level variables. It is executed before main.

26. Can you have multiple init functions?

Yes, but they will be executed in the order they appear.

27. What is an empty struct {}?

An empty struct consumes zero bytes of storage.

28. How do you perform error handling in Go?

By returning an error type and checking it using:

if err != nil { return err
}

29. What is type assertion?

Type assertion is used to extract the underlying value of an interface:

value, ok := x.(string)

30. What is the go fmt command?

go fmt formats Go source code according to the standard style.

31. What is the purpose of go mod?

go mod manages module dependencies in Go projects.

32. How do you create a module?

go mod init module-name

33. What is a package in Go?

A package is a way to group related Go files together.

34. How do you import a package?

import "fmt"

35. What are the visibility rules in Go?

  • Exported identifiers start with an uppercase letter.
  • Unexported identifiers start with a lowercase letter.

36. What is the difference between var and :=?

  • var is used for variable declaration with explicit types.
  • := is used for short variable declaration with inferred types.

37. What is a panic in Go?

panic is used to terminate the program immediately when an error occurs.

38. What is recover?

recover is used to regain control after a panic.

39. How do you use recover?

It is used inside a deferred function:

defer func() { if r := recover(); r != nil { fmt.Println("Recovered:", r) }
}()

40. What is a constant in Go?

Constants are immutable values declared using the const keyword.

41. How do you declare a constant?

const Pi = 3.14

42. What are iota in Go?

iota is a constant generator that increments by 1 automatically.

43. What is go test?

go test is used to run unit tests written in Go.

44. How do you write a test function?

Test functions must start with Test:

func TestAdd(t *testing.T) { result := Add(2, 3) if result != 5 { t.Errorf("expected 5, got %d", result) }
}

45. What is benchmarking in Go?

Benchmarking is used to measure the performance of a function using go test.

46. How do you write a benchmark function?

Benchmark functions must start with Benchmark:

 func BenchmarkAdd(b *testing.B) { for i := 0; i < b.N; i++ { Add(2, 3) } }

47. What is a build constraint?

Build constraints are used to include or exclude files from the build process based on conditions.

48. How do you set a build constraint?

Place the constraint in a comment at the top of the file:

 // +build linux

49. What are slices backed by arrays?

Slices are built on top of arrays and provide a dynamic view over the array.

50. What is garbage collection in Go?

Go automatically manages memory using garbage collection, which frees up memory that is no longer in use.

51. What is the context package in Go?

The context package is used for managing deadlines, cancellation signals, and request-scoped values. It helps in controlling the flow of Goroutines and resources.

52. How do you use context in Go?

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

53. What is sync.WaitGroup?

sync.WaitGroup is used to wait for a collection of Goroutines to finish executing.

54. How do you use sync.WaitGroup?

 var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() // Do some work }() wg.Wait() 

55. What is sync.Mutex?

sync.Mutex provides a lock mechanism to protect shared resources from concurrent access.

56. How do you use sync.Mutex?

var mu sync.Mutex mu.Lock() // critical section mu.Unlock()

57. What is select used for with channels?

select is used to handle multiple channel operations simultaneously, allowing a Goroutine to wait for multiple communication operations.

58. What is go generate?

go generate is a command for generating code. It reads special comments within the source code to execute commands.

59. What are method receivers in Go?

Method receivers specify the type the method is associated with, either by value or pointer:

 func (p *Person) GetName() string { return p.Name }

60. What is the difference between value and pointer receivers?

  • Value receivers get a copy of the original value.
  • Pointer receivers get a reference to the original value, allowing modifications.

61. What are variadic functions?

Variadic functions accept a variable number of arguments:

 func sum(nums ...int) int { total := 0 for _, num := range nums { total += num } return total
}

62. What is a rune in Go?

A rune is an alias for int32 and represents a Unicode code point.

63. What is a select block without a default case?

A select block without a default will block until one of its cases can proceed.

64. What is a ticker in Go?

A ticker sends events at regular intervals:

 ticker := time.NewTicker(time.Second)

65. How do you handle JSON in Go?

Use the encoding/json package to marshal and unmarshal JSON:

 jsonData, _ := json.Marshal(structure) json.Unmarshal(jsonData, &structure)

66. What is go vet?

go vet examines Go source code and reports potential errors, focusing on issues that are not caught by the compiler.

67. What is an anonymous function in Go?

An anonymous function is a function without a name and can be defined inline:

 func() { fmt.Println("Hello") }()

68. What is the difference between == and reflect.DeepEqual()?

  • == checks equality for primitive types.
  • reflect.DeepEqual() compares deep equality of complex types like slices, maps, and structs.

69. What is a time.Duration in Go?

time.Duration represents the elapsed time between two points and is a type of int64.

70. How do you handle timeouts with context?

Use context.WithTimeout to set a timeout:

 ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel()

71. What is a pipeline in Go?

A pipeline is a series of stages connected by channels, where each stage is a collection of Goroutines that receive values from upstream and send values downstream.

72. What is pkg directory convention in Go?

pkg is a directory used to place reusable packages. It is a common convention but not enforced by Go.

73. How do you debug Go code?

Use tools like dlv (Delve), print statements, or the log package.

74. What is type alias in Go?

type aliasing allows you to create a new name for an existing type:

type MyInt = int

75. What is the difference between Append and Copy in slices?

  • append adds elements to a slice and returns a new slice.
  • copy copies elements from one slice to another.
slice1 := []int{1, 2}
slice2 := []int{3, 4}
copy(slice2, slice1) // [1, 2]

76. What is the purpose of go doc?

go doc is used to display documentation for a Go package, function, or variable.

77. How do you handle panics in production code?

Use recover to gracefully handle panics and log them for debugging:

defer func() { if r := recover(); r != nil { log.Println("Recovered from:", r) }
}()

78. What is the difference between map and struct?

  • map is a dynamic data structure with key-value pairs.
  • struct is a static data structure with fixed fields.

79. What is unsafe package?

The unsafe package allows low-level memory manipulation. It is not recommended for regular use.

80. How do you achieve dependency injection in Go?

Use interfaces and constructor functions to pass dependencies, allowing easy mocking and testing.

func NewService(client HttpClient) *Service { return &Service{client: client}
}

Bình luận

Bài viết tương tự

- vừa được xem lúc

Đề thi interview DevOps ở Châu Âu

Well. Chào mọi người, mình là Rice - một DevOps Engineers ở đâu đó tại Châu Âu.

0 0 88

- vừa được xem lúc

5 câu hỏi phỏng vấn Frontend giúp bạn tự tin hơn khi sử dụng bất đồng bộ trong Javascript

Một trong những điều khó khăn khi học Javascript là promises. Chúng không dễ hiểu và có thể cần một vài hướng dẫn và một thời gian kha khá để vận dụng chúng.

0 0 92

- vừa được xem lúc

Một số câu hỏi phỏng vấn liên quan đến SQL mà bạn nên biết^^

Những bài viết trước mình đã chia sẻ những kiến thức cơ bản về Database, MySQL, một số câu lệnh truy vấn cơ sở dữ liệu thường dùng mà các bạn có thể áp dụng vào công việc Tester, QA đang làm như:. MySQL cơ bản: https://link.

0 0 478

- vừa được xem lúc

Phỏng vấn tác giả Proxyman: Từ side project thành full-time business

Phỏng vấn tác giả Proxyman: Từ side project thành full-time business. Bắt đầu từ một pet product để giải quyết những vấn đề cá nhân gặp phải trong.

0 0 38

- vừa được xem lúc

[AI Interview] 12 câu hỏi phỏng vấn Deep Learning siêu hay không thể bỏ qua

Xin chào các bạn, hôm nay mình sẽ quay lại với các bạn về một chủ đề không mới những chưa bao giờ hết hot. Đó chính là các câu hỏi mà thường được hỏi khi phỏng vấn vị trí AI Engineer là gì?.

0 0 231

- vừa được xem lúc

NHỮNG CÂU TRẢ LỜI PHỎNG VẤN QC - MANUAL TESTER - FRESHER LEVEL _ DDTCMT

Em có thể mô tả life cycle của một bug. . . Nguồn hình: https://itguru.

0 0 368