Skip to content

Commit

Permalink
New section: Omit zero value fields
Browse files Browse the repository at this point in the history
Add new section under Initializing Structs that explains that advises
readers to not specify values of fields with zero values per uber-go#109.

Based on discussion in the issue, this adds an exception for cases where
the field name would provide significant context, like test cases.
  • Loading branch information
abhinav committed Mar 4, 2021
1 parent b799fe9 commit 64c88b6
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions style.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ row before the </tbody></table> line.
- [Use Raw String Literals to Avoid Escaping](#use-raw-string-literals-to-avoid-escaping)
- [Initializing Structs](#initializing-structs)
- [Use Field Names to Initialize Structs](#use-field-names-to-initialize-structs)
- [Omit Zero Value Fields in Structs](#omit-zero-value-fields-in-structs)
- [Initializing Struct References](#initializing-struct-references)
- [Initializing Maps](#initializing-maps)
- [Format Strings outside Printf](#format-strings-outside-printf)
Expand Down Expand Up @@ -2837,6 +2838,54 @@ tests := []struct{
}
```

#### Omit Zero Value Fields in Structs

When initializing structs with field names, omit fields that have zero values.
These values will be set by Go automatically.

<table>
<thead><tr><th>Bad</th><th>Good</th></tr></thead>
<tbody>
<tr><td>

```go
user := User{
FirstName: "John",
LastName: "Doe",
MiddleName: "",
Admin: false,
}
```

</td><td>

```go
user := User{
FirstName: "John",
LastName: "Doe",
}
```

</td></tr>
</tbody></table>

This helps reduce noise for readers by omitting values that are default in
that context. Only meaningful values are specified.

Exception: Even with a zero value, field names sometimes provide valuable
context for readers. In particular, test cases in [Test Tables](#test-tables)
can benefit from names of fields even when they are zero-valued.

```go
tests := []struct{
give string
want int
}{
{give: "0", want: 0},
// ...
}
```

#### Initializing Struct References

Use `&T{}` instead of `new(T)` when initializing struct references so that it
Expand Down

0 comments on commit 64c88b6

Please sign in to comment.