-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Closed
Labels
FrozenDueToAgeLanguageChangeSuggested changes to the Go languageSuggested changes to the Go language
Description
by eadfrith:
Go prohibits composite literal expressions for structs with unexported fields. This is good, as it allows the package author to control the way in which instances of such structs are initialized. However, variable declarations for the same structs are allowed to occur without an explicit initializer. The struct is then initialized to its zero value - which may be invalid. Currently there is no way for the package author to prevent a client from creating an invalid instance of a struct. Consider the following silly example: package foo // Incr holds a value and its cached increment type Incr struct { val, ival int; } func NewIncr(v int) Incr { return Incr{v, v+1}; } func (i *Incr) Valid() (bool) { return i.val == i.ival-1; } Client: package main import "foo"; func main() { // intended usage: use factory to create a valid instance valid := foo.NewIncr(1); // compiler blocks composite literals for struct with unexported fields // illegal := foo.Incr{}; // implicit assignment of foo.Incr field 'val' // but declaration without explicit initialization is allowed var invalid foo.Incr; // invalid instance }
Metadata
Metadata
Assignees
Labels
FrozenDueToAgeLanguageChangeSuggested changes to the Go languageSuggested changes to the Go language