Structs
Structs are nominally typed (meaning they must be exactly the same definition to be considered compatbile) data types that can have fields and methods
Example
src/structs.duck
struct Person {
name: String,
age: Int,
} impl {
// static methods are like top level functions (so they can't use self)
static fn new(name: String, age: Int) -> Person {
Person {
name: name,
age: age,
}
}
// mut methods have mutable access to self, meaning they can change the object
mut fn change_name() {
self.name = "Changed";
}
// normal methods may not mutate the object
fn log_self() {
//self.age = 10; <- error (because log_self is not a mut fn)
std::io::println(f"{self.name} is {self.age.to_string()} years old");
}
}
fn main() {
let p = Person::new("John Smith", 43);
p.log_self();
p.change_name();
p.log_self();
}