Structs are useful for defining a type of related fields. Field types can be any of the built-in types or user-defined types for form complex structs.
use fmt;
// Structs are defined with the `type` keyword and fields are added
// within the braces. All fields are accessable to the caller so there
// are now public or private fields like some other languages.
type person = struct {
first_name: str,
last_name: str,
age: u32,
likes: []str,
};
export fn main() void = {
// Create person struct and assign values to all fields.
let p1 = person {
first_name = "Blain",
last_name = "Smith",
age = 43,
likes = ["powerlifting", "tattoos", "heavy metal"],
};
// Access struct fields using dot-notation.
fmt::printf("This struct is {} {}\n",
p1.first_name, p1.last_name)!;
// Reassign values to fields using dot-notation.
p1.age += 1u32;
// Create another person, but only initialize one of the fields
// using the ... operator to initialize the rest to their
// zero-value.
let p2 = person {
first_name = "Austin",
...
};
fmt::printf("p2 '{}' '{}' '{}'\n",
p2.first_name, p2.last_name, p2.age)!;
};
$ hare run structs.ha
4/4 tasks completed (100%)
This struct is Blain Smith
p2 'Austin' '' '0'
Back to table of contents