BeginnerLesson 7 of 16
Structs & Methods – Rust
Custom data types with impl blocks, derive, and constructor functions.
A struct bundles named fields. Behavior goes into an impl block. There are no classes and no inheritance: Rust separates data (struct) from behavior (impl, traits).
struct Rechteck {
breite: f64,
hoehe: f64,
}
impl Rechteck {
fn neu(breite: f64, hoehe: f64) -> Self { // associated function (no self)
Self { breite, hoehe }
}
fn flaeche(&self) -> f64 { // method: borrows self
self.breite * self.hoehe
}
fn skaliere(&mut self, faktor: f64) { // modifies self
self.breite *= faktor;
self.hoehe *= faktor;
}
}
fn main() {
let mut r = Rechteck::neu(3.0, 4.0);
println!("{}", r.flaeche()); // 12
r.skaliere(2.0);
println!("{}", r.flaeche()); // 48
}With #[derive(...)] you let the compiler implement common traits automatically: Debug (output with {:?}), Clone, PartialEq, Default, and many more.
#[derive(Debug, Clone, PartialEq)]
struct Punkt {
x: i32,
y: i32,
}
fn main() {
let p = Punkt { x: 1, y: 2 };
let q = p.clone();
println!("{:?} {}", p, p == q); // Punkt { x: 1, y: 2 } true
println!("{:#?}", p); // formatted over multiple lines
let r = Punkt { x: 10, ..p }; // struct update syntax
println!("{:?}", r); // Punkt { x: 10, y: 2 }
}There are also tuple structs (struct Meter(f64);, handy for “newtypes” with their own type) and unit structs without fields (struct Marker;).
struct Meter(f64);
struct Sekunden(f64);
fn main() {
let strecke = Meter(100.0);
let zeit = Sekunden(9.58);
println!("{:.2} m/s", strecke.0 / zeit.0); // 10.44 m/s
}TipBy convention the constructor is called
new (here neu) and is an ordinary associated function. The shorthand Self { breite, hoehe } works when the variable and the field have the same name.WarningA struct's fields are private to other modules unless you mark them
pub. Access always works within the same module.