Skip to content

Field Access

IsaacShelton edited this page Mar 21, 2022 · 1 revision

Field Access

Fields of a value can be accessed using the . operator.

value.field

The . operator is most commonly used on struct/union values.

struct Point (x, y float)

func main {
    point Point
    point.x = 10
    point.y = point.x
}

Automatic Dereference

When the . operator is used on pointers to struct types, no dereference is required:

point *Point = new Point
defer delete point
point.x = 73
point.y = 21

is allowed instead of having to do:

point *Point = new Point
defer delete point
(*point).x = 73
(*point).y = 21

Usage Example

import basics

struct Point (x, y float)

func main {
    point Point
    point.x = 5
    point.y = 3
    
    printf("Distance to origin = %hf\n", point.distanceToOrigin());
}

func distanceToOrigin(this *Point) float {
    return sqrtf(this.x * this.x + this.y * this.y)
}
Clone this wiki locally