100 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.
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.
以上がGOLANG の面接でよくある質(zhì)問(wèn)の詳細(xì)內(nèi)容です。詳細(xì)については、PHP 中國(guó)語(yǔ) Web サイトの他の関連記事を參照してください。

ホットAIツール

Undress AI Tool
脫衣畫像を無(wú)料で

Undresser.AI Undress
リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover
寫真から衣服を削除するオンライン AI ツール。

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無(wú)料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡(jiǎn)単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無(wú)料のコードエディター

SublimeText3 中國(guó)語(yǔ)版
中國(guó)語(yǔ)版、とても使いやすい

ゼンドスタジオ 13.0.1
強(qiáng)力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

Golangは主にバックエンド開発に使用されますが、フロントエンドフィールドで間接的な役割を果たすこともできます。その設(shè)計(jì)目標(biāo)は、高性能、同時(shí)処理、システムレベルのプログラミングに焦點(diǎn)を當(dāng)てており、APIサーバー、マイクロサービス、分散システム、データベース操作、CLIツールなどのバックエンドアプリケーションの構(gòu)築に適しています。 GolangはWebフロントエンドの主流言語(yǔ)ではありませんが、Gopherjsを介してJavaScriptにコンパイルしたり、Tinygoを介してWebAssemblyで実行したり、テンプレートエンジンを備えたHTMLページを生成してフロントエンド開発に參加できます。ただし、最新のフロントエンド開発は、JavaScript/TypeScriptとそのエコシステムに依存する必要があります。したがって、Golangは、コアとして高性能バックエンドを備えたテクノロジースタック選択により適しています。

GOでGraphQlapiを構(gòu)築するには、GQLGenライブラリを使用して開発効率を向上させることをお?jiǎng)幛幛筏蓼埂?1.最初に、スキーマに基づいた自動(dòng)コード生成をサポートするGQLGENなどの適切なライブラリを選択します。 2。次に、graphqlschemaを定義し、投稿の種類やクエリメソッドの定義など、API構(gòu)造とクエリポータルを説明します。 3。次に、プロジェクトを初期化し、基本コードを生成して、リゾルバにビジネスロジックを?qū)g裝します。 4.最後に、graphqlhandlerをhttpserverに接続し、組み込みの遊び場(chǎng)を介してAPIをテストします。メモには、プロジェクトのメンテナンスを確保するためのフィールドネーミング仕様、エラー処理、パフォーマンスの最適化、セキュリティ設(shè)定が含まれます

GOをインストールするための鍵は、正しいバージョンを選択し、環(huán)境変數(shù)を構(gòu)成し、インストールを検証することです。 1.公式Webサイトにアクセスして、対応するシステムのインストールパッケージをダウンロードします。 Windowsは.msiファイルを使用し、macosは.pkgファイルを使用し、Linuxは.tar.gzファイルを使用し、 /usr /localディレクトリに解凍します。 2.環(huán)境変數(shù)を構(gòu)成し、linux/macOSで?/.bashrcまたは?/.zshrcを編集してパスとgopathを追加し、Windowsがシステムプロパティに移動(dòng)するパスを設(shè)定します。 3.政府コマンドを使用してインストールを確認(rèn)し、テストプログラムを?qū)g行してhello.goを?qū)g行して、編集と実行が正常であることを確認(rèn)します。プロセス全體のパス設(shè)定とループ

sync.waitgroupは、ゴルチンのグループがタスクを完了するのを待つために使用されます。そのコアは、3つの方法で協(xié)力することです。追加、完了、待機(jī)です。 1.ADD(n)待機(jī)するゴルチンの數(shù)を設(shè)定します。 2.done()は各ゴルチンの端で呼び出され、カウントは1つ減少します。 3.wait()すべてのタスクが完了するまでメインコルーチンをブロックします。使用する場(chǎng)合は、注意してください。Goroutineの外部で追加する必要があります。重複を避け、Donが呼び出されていることを確認(rèn)してください。 Deferで使用することをお?jiǎng)幛幛筏蓼埂¥长欷?、Webページの同時(shí)クロール、バッチデータ処理、その他のシナリオで一般的であり、並行性プロセスを効果的に制御できます。

Goの埋め込みパッケージを使用すると、靜的リソースをバイナリに簡(jiǎn)単に埋め込み、Webサービスに適しており、HTML、CSS、寫真、その他のファイルをパッケージ化できます。 1。追加する埋め込みリソースを宣言します// go:embed comment hello.txtを埋め込むなど、変數(shù)の前に埋め込みます。 2。static/*などのディレクトリ全體に埋め込み、embed.fsを介してマルチファイルパッケージを?qū)g現(xiàn)できます。 3.効率を改善するために、ビルドタグまたは環(huán)境変數(shù)を介してディスクロードモードを切り替えることをお?jiǎng)幛幛筏蓼埂?4.パスの精度、ファイルサイズの制限、埋め込みリソースの読み取り専用特性に注意してください。埋め込みの合理的な使用は、展開を簡(jiǎn)素化し、プロジェクト構(gòu)造を最適化することができます。

オーディオとビデオ?jiǎng)I理の中核は、基本的なプロセスと最適化方法を理解することにあります。 1.基本的なプロセスには、取得、エンコード、送信、デコード、再生が含まれ、各リンクには技術(shù)的な困難があります。 2。オーディオおよびビデオの異常、遅延、音のノイズ、ぼやけた畫像などの一般的な問(wèn)題は、同期調(diào)整、コーディング最適化、ノイズ減少モジュール、パラメーター調(diào)整などを通じて解決できます。 3. FFMPEG、OPENCV、WeBRTC、GSTREAMER、およびその他のツールを使用して機(jī)能を達(dá)成することをお?jiǎng)幛幛筏蓼埂?4.パフォーマンス管理の観點(diǎn)から、ハードウェアの加速、解像度フレームレートの合理的な設(shè)定、並行性の制御、およびメモリの漏れの問(wèn)題に注意を払う必要があります。これらの重要なポイントを習(xí)得すると、開発効率とユーザーエクスペリエンスの向上に役立ちます。

GOで書かれたWebサーバーを構(gòu)築することは難しくありません。コアは、Net/HTTPパッケージを使用して基本サービスを?qū)g裝することにあります。 1. Net/HTTPを使用して最もシンプルなサーバーを起動(dòng)します。処理機(jī)能を登録し、數(shù)行のコードを介してポートをリッスンします。 2。ルーティング管理:Servemuxを使用して、構(gòu)造化された管理を容易にするために複數(shù)のインターフェイスパスを整理します。 3。共通の実踐:機(jī)能モジュールによるグループルーティング、およびサードパーティライブラリを使用して複雑なマッチングをサポートします。 4.靜的ファイルサービス:http.fileserverを介してHTML、CSS、JSファイルを提供します。 5。パフォーマンスとセキュリティ:HTTPSを有効にし、リクエスト本體のサイズを制限し、セキュリティとパフォーマンスを改善するためのタイムアウトを設(shè)定します。これらの重要なポイントを習(xí)得した後、機(jī)能を拡大する方が簡(jiǎn)単になります。

Select Plusのデフォルトの目的は、他のブランチがプログラムブロッキングを避ける準(zhǔn)備ができていない場(chǎng)合にデフォルトの動(dòng)作を?qū)g行できるようにすることです。 1.ブロックせずにチャネルからデータを受信すると、チャネルが空の場(chǎng)合、デフォルトのブランチに直接入力されます。 2。時(shí)間と組み合わせて。後またはティッカー、定期的にデータを送信してみてください。チャネルがいっぱいの場(chǎng)合、ブロックしてスキップしません。 3.デッドロックを防ぎ、チャネルが閉じられているかどうかが不確かなときにプログラムが詰まっていることを避けます。それを使用する場(chǎng)合、デフォルトのブランチはすぐに実行され、亂用することはできず、デフォルトとケースは相互に排他的であり、同時(shí)に実行されないことに注意してください。
