9.15 Exercises
-
Defining and Using a Struct
Define a
Rectangle
struct withwidth
andheight
fields. Implement methods to calculate the area and perimeter.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 generic
Pair
struct that holds two values of any type. Implement a method to return 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 a
Book
struct that holds references totitle
andauthor
. Ensure that lifetimes are handled correctly.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
Derive the
Debug
andPartialEq
traits for aPoint
struct. Create instances and compare them.#[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 for
Person
that consumes the instance 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 can no longer be used here }