9.15 Exercises
Click to see the list of suggested exercises
-
Defining and Using a Struct
Define aRectangle
struct withwidth
andheight
. Implement methods forarea
andperimeter
:struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn perimeter(&self) -> u32 { 2 * (self.width + self.height) } } fn main() { let rect = Rectangle { width: 10, height: 20 }; println!("Area: {}", rect.area()); println!("Perimeter: {}", rect.perimeter()); }
-
Generic Struct
Create a genericPair<T, U>
struct holding two values. Implement a method returning a reference to the first value:struct Pair<T, U> { first: T, second: U, } impl<T, U> Pair<T, U> { fn first(&self) -> &T { &self.first } } fn main() { let pair = Pair { first: "Hello", second: 42 }; println!("First: {}", pair.first()); }
-
Struct with References and Lifetimes
Define aBook
struct that references a title and author:struct Book<'a> { title: &'a str, author: &'a str, } fn main() { let title = String::from("Rust Programming"); let author = String::from("John Doe"); let book = Book { title: &title, author: &author, }; println!("{} by {}", book.title, book.author); }
-
Implementing Traits
DeriveDebug
andPartialEq
for aPoint
struct, create instances, and compare:#[derive(Debug, PartialEq)] struct Point { x: i32, y: i32, } fn main() { let p1 = Point { x: 1, y: 2 }; let p2 = Point { x: 1, y: 2 }; println!("{:?}", p1); println!("Points are equal: {}", p1 == p2); }
-
Method Consuming Self
Implement a method that consumes aPerson
and returns thename
:struct Person { name: String, age: u8, } impl Person { fn into_name(self) -> String { self.name } } fn main() { let person = Person { name: String::from("Ivy"), age: 29 }; let name = person.into_name(); println!("Name: {}", name); // person is no longer valid here }