Initialization of fields with zero values
abhinav opened this issue · comments
For struct initialization where some of the fields are zero values, we should establish whether we prefer for those fields to be initialized to zero values explicitly or omitted:
foo := Foo{
Count: 1,
Items: nil,
Default: "",
Admin: true,
}
// or
foo := Foo{
Count: 1,
Admin: true,
}
Opinion: the latter is preferable because it reduces code noise from things that don't matter at this time. You only specify the things that have meaning/value and everything else is the default.
Follow up: When all fields are zero value, do we want to use the explicit struct initialization form or var
?
foo := Foo{}
// or
var foo Foo
Opinion: the latter because it scans differently (visually) and differentiates from Foo{}
where Foo
is a map or slice type (see also, Initializing Maps). It makes it clear that this is something that is probably not going to be used as-is and will be filled separately. ({}
form to initialize structs still applies when not stored in a variable or fields are non-zero: do(Stuff{...})
.)
Agreed on both counts. We also call something similar in the guide already:
However, there are cases where the default value is clearer when the var keyword is used. Declaring Empty Slices, for example.
I think this can be changed to refer more generally to zero values, which would address the 2nd portion of the proposal.
+1 to both.
One caveat for skipping the 0 value in struct initializers is if the 0 value is significant or provides context for the reader. E.g., I often run into test tables where the 0 value is important,
tests := []struct{
s string
want int
}{
{
s: "0",
want: 0,
},
}