Lesson 10 of 20
Structs
Structs
Structs let you group related data together under a named type.
Defining a Struct
struct Point {
x: f64,
y: f64,
}
Creating Instances
let p = Point { x: 1.0, y: 2.0 };
println!("{}", p.x); // 1
Use struct update syntax to create a new instance based on another:
let p2 = Point { x: 3.0, ..p }; // y copied from p
impl Blocks
Methods and associated functions live in impl blocks:
impl Point {
// Associated function (no &self) — called as Point::new(...)
fn new(x: f64, y: f64) -> Self {
Point { x, y }
}
// Method — takes &self
fn distance_to_origin(&self) -> f64 {
(self.x * self.x + self.y * self.y).sqrt()
}
// Mutable method — takes &mut self
fn translate(&mut self, dx: f64, dy: f64) {
self.x += dx;
self.y += dy;
}
}
Tuple Structs
struct Color(u8, u8, u8);
let black = Color(0, 0, 0);
println!("{}", black.0); // 0
Your Task
Implement a Rectangle struct with width and height fields and these methods:
new(width: f64, height: f64) -> Selfarea(&self) -> f64perimeter(&self) -> f64is_square(&self) -> boolscale(&self, factor: f64) -> Rectangle— returns a new scaled rectangle
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.