Using Structs to Structure Related Data1
To run the program:
$ cargo run --bin using-structs
Compiling using-structs v0.1.0 ...
Structs are very simple, basically a (nominal) set of name fields:
struct User {
active: bool,
email: String,
sign_in_count: u64,
}
Otherwise, they work very similar to say, tuples, with some conveniences:
// Avoid typing active: active, email: email, sign_in_count: sign_in_count.
let user = User {
active,
email,
sign_in_count,
};
// Avoid referencing every field manually when creating a new struct.
let user = User {
sign_in_count: user.sign_in_count + 1,
..user
}
There are also tuple structs:
struct Color(i32, i32, i32);
You can also derive behavior, i.e. to use for debugging:
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
let rect = Rectangle {
width: 30,
height: 50,
};
dbg!(&rect);
Using impl
, we can define associated functions, or member-methods:
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn square(size: u32) -> Self {
Self {
width: size,
height: size,
}
}
}
println!("Rectangle's area is {}", rect.area());
let rect = Rectangle::square(10);
println!("Rectangle {:?}'s area is {}", rect, rect.area());