Struct Literals

A struct literal denotes a newly allocated struct value by listing the values of its fields.

You can list just a subset of fields by using the Name: syntax. (And the order of named fields is irrelevant.)

The special prefix & returns a pointer to the struct value.

struct-literals.go

  1. package main
  2. import "fmt"
  3. type Vertex struct {
  4. X, Y int
  5. }
  6. var (
  7. v1 = Vertex{1, 2} // has type Vertex
  8. v2 = Vertex{X: 1} // Y:0 is implicit
  9. v3 = Vertex{} // X:0 and Y:0
  10. p = &Vertex{1, 2} // has type *Vertex
  11. )
  12. func main() {
  13. fmt.Println(v1, p, v2, v3)
  14. }