Golang 面接でよくある 100 の質(zhì)問と回答
1. Golang とは何ですか?
Go、または Golang は、Google によって開発されたオープンソース プログラミング言語です。これは、スケーラブルで高性能なアプリケーションを構(gòu)築するために靜的に型付け、コンパイル、設(shè)計(jì)されています。
2. Go の主な機(jī)能は何ですか?
- ゴルーチンを使用した同時(shí)実行のサポート。
- ガベージコレクション。
- 動(dòng)的動(dòng)作を伴う靜的型付け。
- 単純な構(gòu)文。
- 高速コンパイル。
3. ゴルーチンとは何ですか?
Goroutine は、Go ランタイムによって管理される軽量のスレッドです。これらは、他の関數(shù)またはメソッドと同時(shí)に実行される関數(shù)またはメソッドです。
4. Goroutine はどのように作成しますか?
関數(shù)呼び出しの前に go キーワードを使用します。
go myFunction()
5. Go のチャネルとは何ですか?
チャネルは、ゴルーチンが相互に通信し、実行を同期するための方法です。値の送受信が可能です。
6. チャンネルはどのように宣言しますか?
ch := make(chan int)
7. バッファリングされたチャネルとは何ですか?
バッファされたチャネルには指定された容量があり、バッファがいっぱいになるまで値を送信できます。受信機(jī)が受信できる狀態(tài)になっている必要はありません。
8. チャンネルを閉じるにはどうすればよいですか?
close() 関數(shù)を使用します:
close(ch)
9. Go の構(gòu)造體とは何ですか?
構(gòu)造體は、さまざまなデータ型のフィールドを 1 つのエンティティにグループ化できるユーザー定義型です。
10. 構(gòu)造體はどのように定義しますか?
type Person struct { Name string Age int }
11. Go のインターフェースとは何ですか?
Go のインターフェイスは、メソッド シグネチャのセットを指定する型です。動(dòng)作を定義することでポリモーフィズムが可能になります。
12. インターフェースはどのように実裝しますか?
型は、そのすべてのメソッドを?qū)g裝することによってインターフェイスを?qū)g裝します。
type Animal interface { Speak() string } type Dog struct{} func (d Dog) Speak() string { return "Woof!" }
13. defer キーワードとは何ですか?
defer は、周囲の関數(shù)が戻るまで関數(shù)の実行を延期するために使用されます。
14. 延期はどのように機(jī)能しますか?
遅延関數(shù)は LIFO (後入れ先出し) 順序で実行されます:
defer fmt.Println("world") fmt.Println("hello") // Output: hello world
15. Go のポインタとは何ですか?
ポインタは値のメモリアドレスを保持します。値をコピーする代わりに參照を渡すために使用されます。
16. ポインタはどのように宣言しますか?
var p *int p = &x
17. 新品とメーカーの違いは何ですか?
- new はメモリを割り當(dāng)てますが、値は初期化しません。
- make は、スライス、マップ、チャネルにメモリを割り當(dāng)てて初期化します。
18. Go のスライスとは何ですか?
スライスは、要素のシーケンスをより柔軟に操作する方法を提供する、動(dòng)的にサイズが変更される配列です。
19. スライスはどのように作成しますか?
s := make([]int, 0)
20. Go のマップとは何ですか?
マップはキーと値のペアのコレクションです。
21. 地図はどのように作成しますか?
m := make(map[string]int)
22. select ステートメントとは何ですか?
select を選択すると、Goroutine が複數(shù)の通信操作を待機(jī)できるようになります。
23. 選択はどのように使用しますか?
select { case msg := <-ch: fmt.Println(msg) default: fmt.Println("No message received") }
24. nil チャネルとは何ですか?
nil チャネルは送信操作と受信操作の両方をブロックします。
25. init関數(shù)とは何ですか?
init は、パッケージレベルの変數(shù)を初期化する特別な関數(shù)です。 main の前に実行されます。
26. 複數(shù)の init 関數(shù)を使用できますか?
はい、ただし、表示される順序で実行されます。
27. 空の構(gòu)造體 {} とは何ですか?
空の構(gòu)造體はストレージをゼロバイト消費(fèi)します。
28. Go でエラー処理を行うにはどうすればよいですか?
エラー タイプを返し、以下を使用してチェックします。
if err != nil { return err }
29. 型アサーションとは何ですか?
型アサーションは、インターフェイスの基礎(chǔ)となる値を抽出するために使用されます:
value, ok := x.(string)
30. go fmt コマンドとは何ですか?
go fmt 標(biāo)準(zhǔn)スタイルに従って Go ソース コードをフォーマットします。
31. go modの目的は何ですか?
go mod は Go プロジェクトのモジュールの依存関係を管理します。
32. モジュールはどのように作成しますか?
go mod init module-name
33. Go のパッケージとは何ですか?
パッケージは、関連する Go ファイルをグループ化する方法です。
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.
type HttpClient interface{} func NewService(client HttpClient) *Service { return &Service{client: client} }
81. How does Goroutine differ from a thread?
A Goroutine is a lightweight thread managed by the Go runtime. It differs from OS threads as it uses a smaller initial stack (2KB) and is multiplexed onto multiple OS threads. This makes Goroutines more efficient for handling concurrency.
82. How does the Go scheduler work?
The Go scheduler uses a work-stealing algorithm with M:N scheduling, where M represents OS threads and N represents Goroutines. It schedules Goroutines across available OS threads and CPUs, aiming to balance workload for optimal performance.
83. What is a memory leak, and how do you prevent it in Go?
A memory leak occurs when allocated memory is not released. In Go, it can happen if Goroutines are not terminated or references to objects are kept unnecessarily. Use defer for cleanup and proper cancellation of Goroutines to prevent leaks.
84. How does garbage collection work in Go?
Go uses a concurrent, mark-and-sweep garbage collector. It identifies reachable objects during the mark phase and collects the unreachable ones during the sweep phase, allowing other Goroutines to continue running during collection.
85. Explain differences between sync.Mutex and sync.RWMutex.
- sync.Mutex is used to provide exclusive access to a shared resource.
- sync.RWMutex allows multiple readers or one writer at a time, providing better performance for read-heavy workloads.
86. What are race conditions, and how do you detect them in Go?
Race conditions occur when multiple Goroutines access a shared variable concurrently without proper synchronization. Use go run -race to detect race conditions in Go programs.
87. What is a struct tag, and how is it used?
Struct tags provide metadata for struct fields, often used for JSON serialization:
type User struct { Name string `json:"name"` Age int `json:"age"` }
88. How do you create a custom error in Go?
Create a custom error by implementing the error interface:
type MyError struct { Msg string } func (e *MyError) Error() string { return e.Msg }
89. What is a nil pointer dereference, and how do you avoid it?
A nil pointer dereference occurs when you attempt to access the value a nil pointer points to. Avoid this by checking for nil before using pointers.
90. Explain the difference between sync.Pool and garbage collection.
sync.Pool is used for reusing objects and reducing GC pressure. It provides a way to cache reusable objects, unlike the GC which automatically frees unused memory.
91. How do you implement a worker pool in Go?
Use channels to distribute tasks and manage worker Goroutines:
jobs := make(chan int, 100) for w := 1; w <= 3; w++ { go worker(w, jobs) }
92. What is reflect in Go?
The reflect package allows runtime inspection of types and values. It is used for dynamic operations like inspecting struct fields or methods.
93. What is the difference between buffered and unbuffered channels?
- A buffered channel has a capacity, allowing Goroutines to send data without blocking until the buffer is full.
- An unbuffered channel has no capacity and blocks until the receiver is ready.
94. How do you avoid Goroutine leaks?
Ensure Goroutines are terminated using context for cancellation or using timeouts with channels.
95. What are the key differences between panic and error?
- error is used for handling expected conditions and can be returned.
- panic is used for unexpected conditions and stops the normal flow of execution.
96. Explain the io.Reader and io.Writer interfaces.
io.Reader has a Read method for reading data, while io.Writer has a Write method for writing data. They form the basis of Go's I/O abstractions.
97. What is a nil value interface, and why is it problematic?
A nil value interface is an interface with a nil underlying value. It can cause unexpected behavior when check nil, as an interface with a nil underlying value is not equal to nil.
type MyInterface interface{} var i MyInterface var m map[string]int i = m // This case, m is nil but i not nil
To handle above case, we could use interface assertion as following
if v, ok := i.(map[string]int); ok && v != nil { fmt.Printf("value not nil: %v\n", v) }
98. How do you prevent deadlocks in concurrent Go programs?
To prevent deadlocks, ensure that:
- Locks are always acquired in the same order across all Goroutines.
- Use defer to release locks.
- Avoid holding a lock while calling another function that might acquire the same lock.
- Limit the use of channels within locked sections.
99. How do you optimize the performance of JSON encoding/decoding in Go?
- Use jsoniter or easyjson libraries for faster encoding/decoding than the standard encoding/json.
- Predefine struct fields using json:"field_name" tags to avoid reflection costs.
- Use sync.Pool to reuse json.Encoder or json.Decoder instances when encoding/decoding large JSON data repeatedly.
100. What is the difference between GOMAXPROCS and runtime.Gosched()?
- GOMAXPROCS controls the maximum number of OS threads that can execute Goroutines concurrently. It allows adjusting the parallelism level.
- runtime.Gosched() yields the processor, allowing other Goroutines to run. It does not suspend the current Goroutine but instead gives a chance for the Go scheduler to run other Goroutines.
The above is the detailed content of COMMON GOLANG INTERVIEW QUESTIONS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go compiles the program into a standalone binary by default, the main reason is static linking. 1. Simpler deployment: no additional installation of dependency libraries, can be run directly across Linux distributions; 2. Larger binary size: Including all dependencies causes file size to increase, but can be optimized through building flags or compression tools; 3. Higher predictability and security: avoid risks brought about by changes in external library versions and enhance stability; 4. Limited operation flexibility: cannot hot update of shared libraries, and recompile and deployment are required to fix dependency vulnerabilities. These features make Go suitable for CLI tools, microservices and other scenarios, but trade-offs are needed in environments where storage is restricted or relies on centralized management.

To create a buffer channel in Go, just specify the capacity parameters in the make function. The buffer channel allows the sending operation to temporarily store data when there is no receiver, as long as the specified capacity is not exceeded. For example, ch:=make(chanint,10) creates a buffer channel that can store up to 10 integer values; unlike unbuffered channels, data will not be blocked immediately when sending, but the data will be temporarily stored in the buffer until it is taken away by the receiver; when using it, please note: 1. The capacity setting should be reasonable to avoid memory waste or frequent blocking; 2. The buffer needs to prevent memory problems from being accumulated indefinitely in the buffer; 3. The signal can be passed by the chanstruct{} type to save resources; common scenarios include controlling the number of concurrency, producer-consumer models and differentiation

Goensuresmemorysafetywithoutmanualmanagementthroughautomaticgarbagecollection,nopointerarithmetic,safeconcurrency,andruntimechecks.First,Go’sgarbagecollectorautomaticallyreclaimsunusedmemory,preventingleaksanddanglingpointers.Second,itdisallowspointe

Go is ideal for system programming because it combines the performance of compiled languages ??such as C with the ease of use and security of modern languages. 1. In terms of file and directory operations, Go's os package supports creation, deletion, renaming and checking whether files and directories exist. Use os.ReadFile to read the entire file in one line of code, which is suitable for writing backup scripts or log processing tools; 2. In terms of process management, the exec.Command function of the os/exec package can execute external commands, capture output, set environment variables, redirect input and output flows, and control process life cycles, which are suitable for automation tools and deployment scripts; 3. In terms of network and concurrency, the net package supports TCP/UDP programming, DNS query and original sets.

In Go language, calling a structure method requires first defining the structure and the method that binds the receiver, and accessing it using a point number. After defining the structure Rectangle, the method can be declared through the value receiver or the pointer receiver; 1. Use the value receiver such as func(rRectangle)Area()int and directly call it through rect.Area(); 2. If you need to modify the structure, use the pointer receiver such as func(r*Rectangle)SetWidth(...), and Go will automatically handle the conversion of pointers and values; 3. When embedding the structure, the method of embedded structure will be improved, and it can be called directly through the outer structure; 4. Go does not need to force use getter/setter,

In Go, an interface is a type that defines behavior without specifying implementation. An interface consists of method signatures, and any type that implements these methods automatically satisfy the interface. For example, if you define a Speaker interface that contains the Speak() method, all types that implement the method can be considered Speaker. Interfaces are suitable for writing common functions, abstract implementation details, and using mock objects in testing. Defining an interface uses the interface keyword and lists method signatures, without explicitly declaring the type to implement the interface. Common use cases include logs, formatting, abstractions of different databases or services, and notification systems. For example, both Dog and Robot types can implement Speak methods and pass them to the same Anno

In Go language, string operations are mainly implemented through strings package and built-in functions. 1.strings.Contains() is used to determine whether a string contains a substring and returns a Boolean value; 2.strings.Index() can find the location where the substring appears for the first time, and if it does not exist, it returns -1; 3.strings.ReplaceAll() can replace all matching substrings, and can also control the number of replacements through strings.Replace(); 4.len() function is used to obtain the length of the bytes of the string, but when processing Unicode, you need to pay attention to the difference between characters and bytes. These functions are often used in scenarios such as data filtering, text parsing, and string processing.

TheGoiopackageprovidesinterfaceslikeReaderandWritertohandleI/Ooperationsuniformlyacrosssources.1.io.Reader'sReadmethodenablesreadingfromvarioussourcessuchasfilesorHTTPresponses.2.io.Writer'sWritemethodfacilitateswritingtodestinationslikestandardoutpu
