Go: proposal: spec: require tagged literals for external structs

Created on 27 Jan 2012  ·  8Comments  ·  Source: golang/go

It would aid compatibility and evolution if a package writer knew that all clients
creating structs with types exported from the package use the form
  pkg.Struct{A: a, B: b}
rather than
  pkg.Struct{a, b}

It may be worth making this a language restriction
Go2 LanguageChange NeedsDecision Proposal

Most helpful comment

There is a trick to force users of an exported struct to write field names:

type Struct struct {
    A int
    B string
    _ struct{}
} 

And for any usage of Struct{1, "2"} a simple compile error will appear:

./prog.go:4:16: too few values in Struct literal (Playground https://play.golang.org/p/sPgtcxAoOxd)

(source: https://groups.google.com/forum/#!topic/golang-nuts/NSjVW82i0mY)

All 8 comments

Comment 2:

Not before Go 2.

_Labels changed: added priority-someday, removed priority-later._

Comment 3:

_Labels changed: added repo-main._

Comment 4:

Adding Release=None to all Priority=Someday bugs.

_Labels changed: added release-none._

Comment 5:

_Labels changed: added go2, removed priority-someday._

At present there is a vet check for this:

> go vet
b.go:5:9: pkg.Struct composite literal uses unkeyed fields

Is there an advantage to promoting this check to the language level?

There might be scenarios where it's tedious to have to repeat struct field names over and over again; e.g., for small structs that are frequently created and won't change. Example

p := graphic.Point3D{1, 2, 3}

But for cases like these it's always easy (and probably better) to provide any factory function instead.

There is a trick to force users of an exported struct to write field names:

type Struct struct {
    A int
    B string
    _ struct{}
} 

And for any usage of Struct{1, "2"} a simple compile error will appear:

./prog.go:4:16: too few values in Struct literal (Playground https://play.golang.org/p/sPgtcxAoOxd)

(source: https://groups.google.com/forum/#!topic/golang-nuts/NSjVW82i0mY)

As this is checked by vet today, it does not seem necessary to add to the language proper.

(Perhaps at some future point we should consider promoting some vet checks into the language proper.)

Was this page helpful?
0 / 5 - 0 ratings