Skip to content

Commit

Permalink
Initializing Struct References
Browse files Browse the repository at this point in the history
This adds a recommendation around initilaizing struct references
(`&T{}`). This is a version of the internal section "Using new(T) vs
&T{}".
  • Loading branch information
abhinav committed Jan 23, 2019
1 parent 123162f commit 5620cf3
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions style.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ row before the </tbody></table> line.
- [Reduce Scope of Variables](#reduce-scope-of-variables)
- [Avoid Naked Parameters](#avoid-naked-parameters)
- [Use Raw String Literals to Avoid Escaping](#use-raw-string-literals-to-avoid-escaping)
- [Initializing Struct References](#initializing-struct-references)
- [Format Strings outside Printf](#format-strings-outside-printf)
- [Naming Printf-style Functions](#naming-printf-style-functions)
- [Patterns](#patterns)
Expand Down Expand Up @@ -1788,6 +1789,35 @@ wantError := `unknown error:"test"`
</td></tr>
</tbody></table>

### Initializing Struct References

Use `&T{}` instead of `new(T)` when initializing struct references so that it
looks similar to struct initialization.
<table>
<thead><tr><th>Bad</th><th>Good</th></tr></thead>
<tbody>
<tr><td>
```go
sval := T{Name: "foo"}

// inconsistent
sptr := new(T)
sptr.Name = "bar"
```

</td><td>

```go
sval := T{Name: "foo"}

sptr := &T{Name: "bar"}
```

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

### Format Strings outside Printf

If you declare format strings for `Printf`-style functions outside a string
Expand Down

0 comments on commit 5620cf3

Please sign in to comment.