Read version-dependent struct literal rules
Read version-dependent struct literal rules
In Go 1.23, a keyed struct literal must use direct field names; initialize an embedded or nested value with its own literal. Go 1.27 expands keys to valid field selectors, including promoted fields and nested selector paths. Check the module language version before using the newer syntax. The examples below run on Go 1.23 and remain useful on newer versions.
package main
import ( "fmt")
type Location struct{ City string }type Office struct { Location Floor int}
func main() { o := Office{Location: Location{City: "Lund"}, Floor: 2} fmt.Println(o.City, o.Floor)}The nested literal initializes Location explicitly. The promoted selector o.City can be used to read the field. On Go 1.27+ the alternative Office{City: "Lund", Floor: 2} is permitted when City is unambiguous and the embedded path contains no pointer type. That alternative is documented but not executed here; Go 1.23 rejects it.
Expected output:
Lund 2Initialize pointer fields explicitly
package main
import ( "fmt")
type Info struct{ N int }type Record struct{ *Info }
func main() { r := Record{Info: &Info{N: 8}} fmt.Println(r.N) var zero Record fmt.Println(zero.Info == nil)}Initialize the embedded pointer directly, even on Go 1.27. A promoted literal key cannot traverse an embedded pointer. The newer rules also prohibit specifying an embedded struct and a promoted field inside it as overlapping keys. Omitted fields still receive zero values. Do not dereference the embedded pointer of zero before initialization.
Expected output:
8trueTry it locally
Define Details with Name string and Product embedding Details with Price int. Use a portable nested keyed literal to create name tea and price 5; print both.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced type semantics 08: Read version-dependent struct literal rules
Check the lesson objective before moving on.
Which release allows a promoted field as a struct literal key under the new rules?
Can a promoted key traverse an embedded pointer under the new rule?