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:
|
|
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:
|
|
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 (likeActive
) it’s exported, and thus accessable.
The Tuple Structure:
There really is no way to make a Tuple like structure in Go, like in Rust.
However:
|
|
In the above Point
, it behaves quite similar to the Rust structure.
|
|
The Unit Structure:
Unit-like structures can be useful when you don’t need data, but just need functions…
|
|
Added a function to a structure
Unlike Rust, Go allows you to directly add a function to a structure…
|
|
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.