Idioms and language features
Naked returns
A naked return omits the return values when the function uses named return values. Name the return values in the signature, assign them in the body, then return with no arguments:
func nakedReturn() (a, b string) {
a = "First string" // named return vals
b = "second string"
return // naked return
}
Comma-ok
The comma-ok idiom uses a second boolean return value to distinguish a missing key or failed assertion from a zero value.
Maps
m := map[string]int{"a": 1}
v, ok := m["a"] // v = 1, ok = true
x, ok := m["b"] // x = 0 (zero value), ok = false
Type assertions
var i interface{} = "hello"
s, ok := i.(string) // s = "hello", ok = true
n, ok := i.(int) // n = 0, ok = false
Channel receives
Channel receives use comma-ok to check whether a channel is closed:
- If the channel is open, you receive a value and
okistrue. - If the channel is closed, you receive the zero value for the type and
okisfalse.
ch := make(chan int)
close(ch)
v, ok := <-ch // v = 0, ok = false (channel closed)