More go Flashcards
(24 cards)
Front
Back
How do you define an anonymous function that returns 42?
f := func() int { return 42 }
What’s the Go idiom to defer a function that recovers from panic?
defer func() { if r := recover(); r != nil { … } }()
What happens when you loop with range over a slice and capture the loop variable by reference?
All closures share the same variable, leading to unexpected results.
Pass a context with timeout of 1s:
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
What should you do after creating a cancellable context?
Defer the cancel function to avoid leaks.
Omit empty field Name
from JSON if it’s empty string:
Name string
json:”name,omitempty”``
Difference between Marshal
and Encoder.Encode
?
Marshal
returns []byte; Encode
writes to an io.Writer.
What happens when you read a nonexistent key from a map?
You get the zero value of the value type.
Can you take the address of a map element directly?
No, because map elements are not addressable.
Command to tidy your go.mod file:
go mod tidy
Command to upgrade all direct dependencies:
go get -u ./...
Write a test function for Sum()
in package main:
func TestSum(t *testing.T) { ... }
How to run tests with race detector?
go test -race
What does interface{}
represent in Go?
The empty interface: can hold values of any type.
How do you assert the type of value v
held in interface{}
?
x, ok := v.(TargetType)
What happens if you call Lock()
twice without Unlock()
?
Deadlock.
Difference between Mutex and RWMutex?
RWMutex
allows multiple readers or one writer; Mutex
allows only one locker.
What does io.EOF
signify in Go?
That no more input is available (not necessarily an error).
Read only the first 100 bytes from file f
:
io.LimitReader(f, 100)
How to leak-proof a goroutine that listens on a channel?
Close the channel or use context cancellation.
When is an init()
function run in Go?
Before the main()
function, once per package.
Write a compile-time interface satisfaction check for T
:
var _ MyInterface = (*T)(nil)
Why might you use sync.Pool
?
To reuse temporary objects and reduce GC pressure.