Struct literals

September 26, 2023

Composite literals

For struct literals the following rules apply:

  • A key must be a field name declared in the struct type.

Probably self-evident. You can’t use field names that aren’t defined in the struct type.

  • An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared.
  • If any element has a key, every element must have a key.

Taken together, these rules mean that you have the option to omit the key names in a struct literal, but then you must include all fields, in the order defined in the struct type definition.

type Person struct {
	Name string
	Age int

p1 := Person{Name: "Bob", Age: 42}
p2 := Person{"Bob", 42} // equivalent to p1
p3 := Person{42, "Bob"} // invalid:
                        // cannot use 42 (untyped int constant) as string value in struct literal
                        // cannot use "Bob" (untyped string constant) as int value in struct literal
  • An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
p4 := Person{Name:"Alice"} // Age is omitted, and gets the zero value of 0
  • A literal may omit the element list; such a literal evaluates to the zero value for its type.
p5 := Person{Name:"", Age: 0}
p6 := Person{}  // equivalent to p5
  • It is an error to specify an element for a non-exported field of a struct belonging to a different package.
package foo

type Person struct {
  Name      string
  passsword string
package bar

import "foo"

var p = bar.Person{password:"secret"} // Invalid

The spec goes on to provide its own examples of a couple of the above concepts:

Given the declarations

type Point3D struct { x, y, z float64 }
type Line struct { p, q Point3D }

one may write

origin := Point3D{}                            // zero value for Point3D
line := Line{origin, Point3D{y: -4, z: 12.3}}  // zero value for line.q.x

Quotes from The Go Programming Language Specification Version of August 2, 2023

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .