Initialize keyed and positional literals
Initialize keyed and positional literals
A struct composite literal can name fields explicitly (keyed) or supply values in declaration order (positional). Keyed literals can omit fields; omitted fields receive their zero values. A positional literal with elements must supply every field in order.
package main
import ( "fmt")
type Point struct{ X, Y int }
func main() { a := Point{X: 3} b := Point{3, 0} fmt.Println(a.X, a.Y, a == b)}Both literals create the same value. The keyed version makes the coordinate explicit. A keyed literal cannot repeat a field or mix keyed and positional elements. Prefer keyed literals for maintainability, especially across package boundaries.
Expected output:
3 0 trueCreate a pointer with a literal
package main
import ( "fmt")
type Config struct { Port int Host string}
func main() { p := &Config{Host: "local"} fmt.Println(p.Host, p.Port) p.Port = 8080 fmt.Println(p.Port)}&Config{...} creates a pointer to a new variable initialized with that literal. It does not impose validation or defaults beyond the supplied values and the zero values. Go permits an empty literal Config{}.
Expected output:
local 08080Try it locally
Define Size with Width and Height int. Create Size{Height:5} and print Width and Height. Then create Size{2,5} and print both fields.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structs and defined types 03: Initialize keyed and positional literals
Check the lesson objective before moving on.
What happens to omitted fields in keyed literals?
Which literal is valid for struct{X,Y int}?