>

Structures

Go, like Rust, doesn’t have classes.

Go’s structs aren’t much different than Rust’s [structs]({{ ref “/rust/structs”}}), in that they can have the same 3 types…

Adding functionality to structures is different than Rust’s structures… See here for all three of the structure types.

The regular struct:

Top

1
2
3
4
5
6
type User struct {
    active bool
    username string
    email string
    sign_in_count uint64
}

The above struct has a boolean field active, 2 string fields username and email, and a unsigned 64-bit integer (uint64) sign_in_count.

This example shows that Go’s structure looks quite similar to Rust’s structure.

To initialize an instance of the struct:

1
2
3
4
5
6
7
8
func main() {
    var u User = User{
        active: true,
        username: "apollo",
        email: "[email protected]",
        sign_in_count: 1,
    }
}

So if we want to access any of this User, we can access it directly… with a twist.

In out example, User structure has 4 unexported fields… this means outside the package, these fields can’t be accessed directly.

In Go, to prevent fields that shouldn’t be accessed, if the field isn’t capitalized (like active) it’s unexported. Meanwhile, if it is capitalized (like Active) it’s exported, and thus accessable.

The Tuple Structure:

Top

There really is no way to make a Tuple like structure in Go, like in Rust.

However:

1
type Point [2]int32

In the above Point, it behaves quite similar to the Rust structure.

1
2
3
4
5
6
import "fmt"

func main() {
    var p Point = Point{3, 5}
    fmt.Printf("x: %d y: %d\n", p[0], p[1])
}

The Unit Structure:

Top

Unit-like structures can be useful when you don’t need data, but just need functions…

1
2
3
4
5
type AlwaysEqual struct{}

func main() {
    var subject AlwaysEqual = AlwaysEqual{}
}

Added a function to a structure

Unlike Rust, Go allows you to directly add a function to a structure…

1
2
3
4
5
type Point [2]int32

func (p *Point) IsZero() bool {
    return p[0] == 0 && p[1] == 0
}

The above adds a IsZero function, to check if the Point is 0 on both the X, and Y (or in this case, index 0, and index 1).

Rust however uses impl, implementation block, to add functions to structures.


2023-11-09