wiki/content/20200828181259-structs.md

930 B

id title
463ce364-f426-4089-a0ca-ffe45f0461f2 Golang Structs

Basics

Golang structs are what you expect

package main

import "fmt"

type Vertex struct {
    X int
    Y int
}

func main() {
    fmt.Println(Vertex{1, 2})
}

Struct fields

Struct fields are accessed using a dot

package main

import "fmt"

type Coorindate struct {
    X int
    Y int
}

func main() {
    coordinate := Coorindate{1, 67}
    coordinate.X = 26
    fmt.Println(coordinate.X)
}

Struct literals

You can also newly allocate a struct by listing the values of its fields. This is known as a "struct literal" (duh)

package main

import "fmt"

type Vertex struct {
    X, Y int
}

var (
    v1 = Vertex{1, 2}  // has type Vertex
    v2 = Vertex{X: 1}  // Y:0 is implicit
    v3 = Vertex{}      // X:0 and Y:0
    p  = &Vertex{1, 2} // has type *Vertex
)

func main() {
    fmt.Println(v1, p, v2, v3)
}