複合リテラル
複合リテラルは名前付きを使うこと。無名の場合、構造体のレイアウトが変わった時にコンパイルできなくなったり、型が同じで順番が変わった場合に値の意味がバグとなる。
https://groups.google.com/g/golang-nuts/c/Ub1GMMrfgFc
ただしテーブルドリブンテストで使うだけの構造体などは、定義のすぐ近くで使っているので壊れても問題ない。
Struct literals. For the addition of features in later point releases, it may be necessary to add fields to exported structs in the API. Code that uses unkeyed struct literals (such as pkg.T{3, “x”}) to create values of these types would fail to compile after such a change. However, code that uses keyed literals (pkg.T{A: 3, B: “x”}) will continue to compile after such a change. We will update such data structures in a way that allows keyed struct literals to remain compatible, although unkeyed literals may fail to compile. (There are also more intricate cases involving nested data structures or interfaces, but they have the same resolution.) We therefore recommend that composite literals whose type is defined in a separate package should use the keyed notation.
互換性は壊してはいけない。ビルドエラーになった方が気付きやすくて良いという意見もあるが、大きなプロダクトの一部で使われている場合に、AとBで使われていて片方が新しいバージョンを使ったとすると、もう片方をアップデートするまではエラーが解消されない。
互換性を維持する方法はいくつもあるが、モジュールのブログを読むといい。
- Part 1 — Using Go Modules
- Part 2 — Migrating To Go Modules
- Part 3 — Publishing Go Modules
- Part 4 — Go Modules: v2 and Beyond
- Part 5 — Keeping Your Modules Compatible
構造体フィールドの先頭にプライベートメンバーを入れておくことで、パッケージの外から名前無しで初期化されることを防ぐ。