notexOPENOverview
Notex/Languages/The Zero Value Versus No Value
04.09LESSON 09 OF 20 · 1 MIN READ

The Zero Value Versus No Value

Always free to read

Go pointers are often used to indicate the difference between a variable or field that’s been assigned the zero value and one that hasn’t been assigned a value at all. If this distinction matters in your program, use a nil pointer to represent the unassigned variable or struct field.

Because pointers also indicate mutability, be careful when using this pattern. Rather than return a pointer set to nil from a function, use the comma ok idiom that you saw for maps and return a value type and a Boolean.

Remember, if a nil pointer is passed into a function via a parameter or a field on a parameter, you cannot set the value within the function because there’s nowhere to store it. If a non-nil value is passed in for the pointer, do not modify it unless you document the behavior.

Again, JSON conversions are the exception that proves the rule. When converting data back and forth from JSON, you often need a way to differentiate between the zero value and not having a value assigned at all. Use a pointer value for fields in the struct that are nullable.

When you aren’t working with JSON (or other external protocols), resist the temptation to use a pointer field to indicate no value. While a pointer is a handy way to indicate no value, if you aren’t going to modify the value, use a value type instead, paired with a Boolean.

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K