Structs

A struct is a collection of fields. Struct fields are accessed using a dot.

Example

package main

import "fmt"

type Vertex struct {
    X int
    Y int
}

func main() {
    fmt.Println(Vertex{1, 2})
    
    v := Vertex{1, 2}
    v.X = 4
    fmt.Println(v.X)
}
{1 2}
4

Pointers to Structs

Struct fields can also be accessed using a struct pointer.

We could write (*p).X to access the field X of the Vertex struct. However, this is a cumbersome notation. So, Go allows us to use p.X without this explicit derefence.

Struct Literals

A struct literal denotes a newly allocated struct value by listing the values of its fields. The predix & returns a pointer to the struct value.

Last updated

Was this helpful?