comma ok idiom
The Go pattern of receiving a second true-or-false result, as in value, ok := m[key], to learn whether an operation really found something.
In more detail
For a map, ok is false when the key is missing, which separates absent from a stored zero. The same form checks type assertions, os.LookupEnv and receives from a closed channel. Use it whenever a zero value could be a real answer.
Example
port, ok := ports["ssh"]
if !ok {
fmt.Println("ssh is absent")
}Related terms
- map — A Go collection that stores values by key, such as service name to port number, and looks them up quickly.
- type assertion — An expression such as value.(string) that gets the concrete value out of an interface, if it really holds that type.
- os.LookupEnv — The Go function that returns an environment variable's value and a boolean saying whether it was set at all.
- Boolean — A value that can only be true or false.
Taught in
- Arrays, Slices, and Maps — Concurrent Systems Programming with Go
- Type Assertions and the Empty Interface — Concurrent Systems Programming with Go
- Channels and Synchronization — Concurrent Systems Programming with Go