Search⌘ K

The comma, ok Pattern

Explore the comma ok pattern in Go to write clear and concise error handling, map key existence checks, type assertions, and channel state checks, helping you produce idiomatic and effective Go code.

While studying the Go-language, we encountered several times the so-called comma, ok idiom where an expression returns two values: the first of which is a value or nil, and the second is true/false or an error. An if-condition with initialization and then testing on the second-value leads to succinct and elegant code. This is a significant pattern in idiomatic Go-code. Here are all cases summarized:

Testing for errors on function return

var value Type_value
var err error
if value, err = pack1.Func1(param1); err != nil
...