mtchuyen / Golang-Tips

Tips in Golang programming
3 stars 2 forks source link

Golang Interview #11

Open mtchuyen opened 3 years ago

mtchuyen commented 3 years ago

50-golang-interview-questions

https://www.educative.io/blog/50-golang-interview-questions

mtchuyen commented 3 years ago

How To Crack the Top 25 Golang Interview Questions

https://betterprogramming.pub/how-to-crack-the-top-25-golang-interview-questions-a94396d6c808

mtchuyen commented 2 years ago

50 mistakes commonly made by Golang developers

https://www.programmersought.com/article/8997224148/

mtchuyen commented 2 years ago

In conversation with Go-Lang

https://adityagoel123.medium.com/in-conversation-with-go-lang-part1-57753b03072e

https://adityagoel123.medium.com/in-conversation-with-go-langs-datatypes-part2-fa0b7ca98725

mtchuyen commented 2 years ago

Golang Technical Interview

Golang Technical Interview @TCMLabs Source: https://blog.tcmlabs.fr/golang-technical-interview-tcmlabs-a70c02639381

Here is a sample of those questions, sorted by level of experience.

Level 0: The Basics

Level 1: The fundamentals

Level 2: Let’s be serious

func (o obj) Call() err
---
func (o *obj) Call() err
type Blob struct {
  Name  string `json:"name"`
  Age   string `json:"order"`
}
func main() {
  var blob []Blob
  var jsonBlob = []byte(`[
      {"name": "Adam", "age": "10"},
      {"name": "Eve",    "age": "100"}
    ]`)
  json.Unmarshal(jsonBlob, &blob)
}
--------------------------------------------------------------------
func main() {
  var blob []map[string]interface{}
  var jsonBlob = []byte(`[
      {"name": "Adam", "age": "10"},
      {"name": "Eve",    "age": "100"}
    ]`)
  json.Unmarshal(jsonBlob, &blob)
}

Explain what this is doing? Compare it to the code from the previous question?

func main() {
  var blob []map[string]interface{}
  var jsonBlob = []byte(`[
      {"name": "Adam", "age": "10"},
      {"name": "Eve",    "age": "100"}
    ]`)
  json.NewDecoder(bytes.NewReader(jsonBlob)).Decode(&blob)
}

Level 3: I know Golang

ch := make(chan int)
ch <- 7
res := <- ch
fmt.Println(res)

Level 4: I develop web servers

func (f [HandlerFunc](https://pkg.go.dev/net/http#HandlerFunc)) ServeHTTP(w [ResponseWriter](https://pkg.go.dev/net/http#ResponseWriter), r *[Request](https://pkg.go.dev/net/http#Request))

type HandlerFunc func([ResponseWriter](https://pkg.go.dev/net/http#ResponseWriter), *[Request](https://pkg.go.dev/net/http#Request))

type Handler interface {
  ServeHTTP([ResponseWriter](https://pkg.go.dev/net/http#ResponseWriter), *[Request](https://pkg.go.dev/net/http#Request))
}

func ListenAndServe(addr [string](https://pkg.go.dev/builtin#string), handler [Handler](https://pkg.go.dev/net/http#Handler)) [error](https://pkg.go.dev/builtin#error)

package main

import ( "fmt" "log" "net/http" )

func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) }

func main() { http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) }


- Explain this code and compare it to the previous question:

type Layer0 struct { }

func (l Layer0) ServeHTTP(w http.ResponseWriter, r http.Request) { if r.URL.Path[1:] == "test" { fmt.Fprintf(w, "Test page") } http.Error(w, "Page Not Found", http.StatusNotFound) }

func main() { myServer := &Layer0{} http.ListenAndServe(":8080", myServer) }



- What are the advantages and drawbacks of using a go router?
mtchuyen commented 10 months ago

20 Intermediate level golang interview questions

Source: https://dsysd-dev.medium.com/20-intermediate-level-golang-interview-questions-da11917acb51

What is the purpose of a Goroutine in Golang?

Goroutines enable concurrent execution in Golang, allowing functions to run concurrently without blocking each other.

How do you handle concurrent access to shared resources in Golang?

Golang provides synchronization primitives like mutexes and channels to safely access and modify shared resources in concurrent scenarios.

What is the difference between a defer statement and a panic in Golang?

A defer statement schedules a function call to be executed later, while a panic is a runtime error that triggers immediate program termination.

How do you implement error handling in Golang?

Golang uses the error type to handle and propagate errors. Functions often return an error as the last return value, which can be checked for nil to identify errors.

What is the purpose of the context package in Golang?

The context package provides a mechanism for managing Goroutines and handling cancellation or timeouts in a controlled manner.

How do you perform unit testing in Golang?

Golang has a built-in testing package called testing. You can write test functions with names starting with Test and use the go test command to run the tests.

What are pointers in Golang, and how are they used?

Pointers in Golang hold the memory addresses of values. They are used to indirectly access and modify values, allowing efficient memory management and in-place modifications.

Explain the difference between shallow copy and deep copy in Golang.

Shallow copy creates a new copy of the structure but references the same underlying data, while deep copy creates a new copy with new, separate data.

What are interfaces in Golang, and how are they used?

Interfaces define a set of method signatures. Types that implement these methods implicitly satisfy the interface, allowing polymorphism and abstraction.

How do you handle JSON encoding and decoding in Golang?

Golang provides the encoding/json package to encode Go types into JSON and decode JSON into Go types using the json.Marshal and json.Unmarshal functions.

What is the purpose of the sync.WaitGroup in Golang?

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

What is the purpose of the sync.Pool in Golang?

The sync.Pool provides a pool of reusable objects, allowing efficient memory reuse and reducing the overhead of object allocation.

How do you handle command-line arguments in Golang?

Command-line arguments can be accessed using the os.Args variable, which provides a slice of strings representing the command-line arguments.

Explain the concept of middleware in the context of web development in Golang.

Middleware in Golang is used to intercept and process HTTP requests and responses, allowing common functionalities like authentication, logging, or rate limiting to be shared across multiple routes.

How do you handle file operations in Golang?

Golang provides the os package for file operations. You can use functions like os.Open, os.Create, and os.ReadFile to work with files.

What is reflection in Golang, and how is it used?

Reflection in Golang enables the inspection of types, values, and structs at runtime. It allows dynamic type checks and accessing and manipulating data without knowing the type at compile-time.

How does Golang handle error handling and error propagation in its standard library?

Golang encourages returning errors explicitly as a return value and provides functions like errors.New and fmt.Errorf for creating and formatting errors.

What is the purpose of the go.mod file in Golang?

The go.mod file is used to define and manage the dependencies of a Golang project. It allows versioning and tracking of external packages used in the project.

How do you perform database operations in Golang?

Golang provides various database drivers and packages, such as database/sql, to interact with databases. These packages offer functions for connecting, querying, and modifying database data.

Explain the concept of method receivers in Golang.

Method receivers in Golang are special types of functions associated with a struct or a type. They allow performing actions or computations on the values of that type.

mtchuyen commented 10 months ago

When in doubt, use a pointer receiver https://groups.google.com/g/golang-nuts/c/Qb4IAEbpziU

There are six (6) permutations of an interface and the variable of the interface type, two (2) of which will not compile:

  1. A value variable and multiple value receivers <--- compiles
  2. A pointer variable and multiple value receivers <--- compiles
  3. A pointer variable and multiple pointer receivers. <--- compiles
  4. A value variable and multiple pointer receivers. <--- will NOT compile
  5. A pointer variable and mixed value+pointer receivers <--- compiles
  6. A value variable and mixed value+pointer receivers. <--- will NOT compile

Permutation #4 and #6 are consistent with the description above, and they both have a value variable in common.