Lesson 13 of 50 · rust
Structs
Duration: 15 minutes
Lesson 13 of 50 · rust
Duration: 15 minutes
rust\nstruct Point {\n x: f64,\n y: f64,\n}\n\nstruct Person {\n name: String,\n age: u32,\n email: String,\n}\n\n\n## Creating Struct Instances\n\nrust\nfn main() {\n let p = Point { x: 1.0, y: 2.0 };\n println!(\"Point: ({}, {})\", p.x, p.y);\n \n let person = Person {\n name: String::from(\"Alice\"),\n age: 30,\n email: String::from(\"alice@example.com\"),\n };\n println!(\"Person: {}, age {}\", person.name, person.age);\n}\n\n\n## Struct Field Init Shorthand\n\nrust\nfn create_person(name: String, age: u32) -> Person {\n Person {\n name, // Equivalent to name: name\n age, // Equivalent to age: age\n email: String::from(\"no-reply@example.com\"),\n }\n}\n\n\n## Struct Update Syntax\n\nCreate a new struct from an existing one:\n\nrust\nlet person1 = Person {\n name: String::from(\"Alice\"),\n age: 30,\n email: String::from(\"alice@example.com\"),\n};\n\nlet person2 = Person {\n name: String::from(\"Bob\"),\n ..person1 // Copy remaining fields from person1\n};\n\n\n## Tuple Structs\n\nStructs without named fields:\n\nrust\nstruct Color(u8, u8, u8);\nstruct Point(f64, f64);\n\nlet black = Color(0, 0, 0);\nlet origin = Point(0.0, 0.0);\n\n\n## Unit-Like Structs\n\nStructs without any fields:\n\nrust\nstruct Marker;\n\n\n## Methods on Structs\n\nDefine functions associated with structs using impl:\n\nrust\nimpl Point {\n fn distance_from_origin(&self) -> f64 {\n (self.x.powi(2) + self.y.powi(2)).sqrt()\n }\n \n fn move_by(&mut self, dx: f64, dy: f64) {\n self.x += dx;\n self.y += dy;\n }\n \n fn new(x: f64, y: f64) -> Point {\n Point { x, y }\n }\n}\n\nfn main() {\n let mut p = Point::new(3.0, 4.0);\n println!(\"Distance: {}\", p.distance_from_origin()); // 5.0\n p.move_by(1.0, 1.0);\n}\n\n\n## Associated Functions\n\nFunctions called with :: syntax (like Point::new):\n\nrust\npub struct User {\n username: String,\n email: String,\n}\n\nimpl User {\n pub fn new(username: String, email: String) -> User {\n User { username, email }\n }\n \n pub fn display(&self) {\n println!(\"User: {}, Email: {}\", self.username, self.email);\n }\n}\n\n\n## Debugging Structs\n\nrust\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nfn main() {\n let rect = Rectangle { width: 30, height: 50 };\n println!(\"Rectangle: {:?}\", rect); // ERROR: doesn't implement Debug\n}\n\n\nAdd #[derive(Debug)] to enable debug printing:\n\nrust\n#[derive(Debug)]\nstruct Rectangle {\n width: u32,\n height: u32,\n}\n\nfn main() {\n let rect = Rectangle { width: 30, height: 50 };\n println!(\"Rectangle: {:?}\", rect);\n}\n