백엔드 개발 Golang 일반적인 GOLANG 인터뷰 질문

일반적인 GOLANG 인터뷰 질문

Oct 18, 2024 pm 02:09 PM

COMMON GOLANG INTERVIEW QUESTIONS

Golang 面接でよくある 100 の質問と回答

1. Golang とは何ですか?

Go、または Golang は、Google によって開発されたオープンソース プログラミング言語です。これは、スケーラブルで高性能なアプリケーションを構築するために静的に型付け、コンパイル、設計されています。

2. Go の主な機能は何ですか?

  • ゴルーチンを使用した同時実行のサポート。
  • ガベージコレクション。
  • 動的動作を伴う静的型付け。
  • 単純な構文。
  • 高速コンパイル。

3. ゴルーチンとは何ですか?

Goroutine は、Go ランタイムによって管理される軽量のスレッドです。これらは、他の関数またはメソッドと同時に実行される関数またはメソッドです。

4. Goroutine はどのように作成しますか?

関数呼び出しの前に go キーワードを使用します。

   go myFunction()
로그인 후 복사

5. Go のチャネルとは何ですか?

チャネルは、ゴルーチンが相互に通信し、実行を同期するための方法です。値の送受信が可能です。

6. チャンネルはどのように宣言しますか?

   ch := make(chan int)
로그인 후 복사

7. バッファリングされたチャネルとは何ですか?

バッファされたチャネルには指定された容量があり、バッファがいっぱいになるまで値を送信できます。受信機が受信できる状態になっている必要はありません。

8. チャンネルを閉じるにはどうすればよいですか?

close() 関数を使用します:

   close(ch)
로그인 후 복사

9. Go の構造体とは何ですか?

構造体は、さまざまなデータ型のフィールドを 1 つのエンティティにグループ化できるユーザー定義型です。

10. 構造体はどのように定義しますか?

   type Person struct {
    Name string
    Age  int
   }
로그인 후 복사

11. Go のインターフェースとは何ですか?

Go のインターフェイスは、メソッド シグネチャのセットを指定する型です。動作を定義することでポリモーフィズムが可能になります。

12. インターフェースはどのように実装しますか?

型は、そのすべてのメソッドを実装することによってインターフェイスを実装します。

    type Animal interface {
       Speak() string
    }

    type Dog struct{}

    func (d Dog) Speak() string {
        return "Woof!"
    }
로그인 후 복사

13. defer キーワードとは何ですか?

defer は、周囲の関数が戻るまで関数の実行を延期するために使用されます。

14. 延期はどのように機能しますか?

遅延関数は LIFO (後入れ先出し) 順序で実行されます:

   defer fmt.Println("world")
   fmt.Println("hello")
   // Output: hello world
로그인 후 복사

15. Go のポインタとは何ですか?

ポインタは値のメモリアドレスを保持します。値をコピーする代わりに参照を渡すために使用されます。

16. ポインタはどのように宣言しますか?

   var p *int
   p = &x
로그인 후 복사

17. 新品とメーカーの違いは何ですか?

  • new はメモリを割り当てますが、値は初期化しません。
  • make は、スライス、マップ、チャネルにメモリを割り当てて初期化します。

18. Go のスライスとは何ですか?

スライスは、要素のシーケンスをより柔軟に操作する方法を提供する、動的にサイズが変更される配列です。

19. スライスはどのように作成しますか?

   s := make([]int, 0)
로그인 후 복사

20. Go のマップとは何ですか?

マップはキーと値のペアのコレクションです。

21. 地図はどのように作成しますか?

   m := make(map[string]int)
로그인 후 복사

22. select ステートメントとは何ですか?

select を選択すると、Goroutine が複数の通信操作を待機できるようになります。

23. 選択はどのように使用しますか?

   select {
    case msg := <-ch:
        fmt.Println(msg)
    default:
        fmt.Println("No message received")
    }
로그인 후 복사

24. nil チャネルとは何ですか?

nil チャネルは送信操作と受信操作の両方をブロックします。

25. init関数とは何ですか?

init は、パッケージレベルの変数を初期化する特別な関数です。 main の前に実行されます。

26. 複数の init 関数を使用できますか?

はい、ただし、表示される順序で実行されます。

27. 空の構造体 {} とは何ですか?

空の構造体はストレージをゼロバイト消費します。

28. Go でエラー処理を行うにはどうすればよいですか?

エラー タイプを返し、以下を使用してチェックします。

   if err != nil {
    return err
   }
로그인 후 복사

29. 型アサーションとは何ですか?

型アサーションは、インターフェイスの基礎となる値を抽出するために使用されます:

   value, ok := x.(string)
로그인 후 복사

30. go fmt コマンドとは何ですか?

go fmt 標準スタイルに従って 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.

위 내용은 일반적인 GOLANG 인터뷰 질문의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Golang vs. Python : 성능 및 확장 성 Golang vs. Python : 성능 및 확장 성 Apr 19, 2025 am 12:18 AM

Golang은 성능과 확장 성 측면에서 Python보다 낫습니다. 1) Golang의 컴파일 유형 특성과 효율적인 동시성 모델은 높은 동시성 시나리오에서 잘 수행합니다. 2) 해석 된 언어로서 파이썬은 천천히 실행되지만 Cython과 같은 도구를 통해 성능을 최적화 할 수 있습니다.

Golang 및 C : 동시성 대 원시 속도 Golang 및 C : 동시성 대 원시 속도 Apr 21, 2025 am 12:16 AM

Golang은 동시성에서 C보다 낫고 C는 원시 속도에서 Golang보다 낫습니다. 1) Golang은 Goroutine 및 Channel을 통해 효율적인 동시성을 달성하며, 이는 많은 동시 작업을 처리하는 데 적합합니다. 2) C 컴파일러 최적화 및 표준 라이브러리를 통해 하드웨어에 가까운 고성능을 제공하며 극도의 최적화가 필요한 애플리케이션에 적합합니다.

GOT GO로 시작 : 초보자 가이드 GOT GO로 시작 : 초보자 가이드 Apr 26, 2025 am 12:21 AM

goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity, 효율성, 및 콘크리 론 피처

Golang vs. C : 성능 및 속도 비교 Golang vs. C : 성능 및 속도 비교 Apr 21, 2025 am 12:13 AM

Golang은 빠른 개발 및 동시 시나리오에 적합하며 C는 극도의 성능 및 저수준 제어가 필요한 시나리오에 적합합니다. 1) Golang은 쓰레기 수집 및 동시성 메커니즘을 통해 성능을 향상시키고, 고전성 웹 서비스 개발에 적합합니다. 2) C는 수동 메모리 관리 및 컴파일러 최적화를 통해 궁극적 인 성능을 달성하며 임베디드 시스템 개발에 적합합니다.

Golang의 영향 : 속도, 효율성 및 단순성 Golang의 영향 : 속도, 효율성 및 단순성 Apr 14, 2025 am 12:11 AM

goimpactsdevelopmentpositively throughlyspeed, 효율성 및 단순성.

C와 Golang : 성능이 중요 할 때 C와 Golang : 성능이 중요 할 때 Apr 13, 2025 am 12:11 AM

C는 하드웨어 리소스 및 고성능 최적화가 직접 제어되는 시나리오에 더 적합하지만 Golang은 빠른 개발 및 높은 동시성 처리가 필요한 시나리오에 더 적합합니다. 1.C의 장점은 게임 개발과 같은 고성능 요구에 적합한 하드웨어 특성 및 높은 최적화 기능에 가깝습니다. 2. Golang의 장점은 간결한 구문 및 자연 동시성 지원에 있으며, 이는 동시성 서비스 개발에 적합합니다.

Golang vs. Python : 주요 차이점과 유사성 Golang vs. Python : 주요 차이점과 유사성 Apr 17, 2025 am 12:15 AM

Golang과 Python은 각각 고유 한 장점이 있습니다. Golang은 고성능 및 동시 프로그래밍에 적합하지만 Python은 데이터 과학 및 웹 개발에 적합합니다. Golang은 동시성 모델과 효율적인 성능으로 유명하며 Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명합니다.

Golang 및 C : 성능 상충 Golang 및 C : 성능 상충 Apr 17, 2025 am 12:18 AM

Golang과 C의 성능 차이는 주로 메모리 관리, 컴파일 최적화 및 런타임 효율에 반영됩니다. 1) Golang의 쓰레기 수집 메커니즘은 편리하지만 성능에 영향을 줄 수 있습니다. 2) C의 수동 메모리 관리 및 컴파일러 최적화는 재귀 컴퓨팅에서 더 효율적입니다.

See all articles