Skip to main content

Github

πŸ¦€ Rust Structs

·298 words·2 mins·

Rust Structs #

Structs let you create custom types that group related data together. They’re similar to tuples, but each piece of data has a name.

Defining Structs #

Define a struct using the struct keyword:

struct User {
 active: bool,
 username: String,
 email: String,
 sign_in_count: u64,
}
fn main() {
 let user1 = User {
 email: String::from("[email protected]"),
 username: String::from("someusername123"),
 active: true,
 sign_in_count: 1,
 };
 
 println!("User email: {}", user1.email);
}

Mutable Structs #

The entire struct must be mutable to change fields:

fn main() {
 let mut user1 = User {
 email: String::from("[email protected]"),
 username: String::from("someusername123"),
 active: true,
 sign_in_count: 1,
 };
 
 user1.email = String::from("[email protected]");
}

Struct Update Syntax #

Create instances from other instances:

fn main() {
 let user1 = User {
 email: String::from("[email protected]"),
 username: String::from("someusername123"),
 active: true,
 sign_in_count: 1,
 };
 
 let user2 = User {
 email: String::from("[email protected]"),
 ..user1 // Use remaining fields from user1
 };
}

Tuple Structs #

Structs without named fields:

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
fn main() {
 let black = Color(0, 0, 0);
 let origin = Point(0, 0, 0);
 
 println!("First color value: {}", black.0);
}

Unit-Like Structs #

Structs without any fields:

struct AlwaysEqual;
fn main() {
 let subject = AlwaysEqual;
}

Method Syntax #

Define methods within an impl block:

struct Rectangle {
 width: u32,
 height: u32,
}
impl Rectangle {
 fn area(&self) -> u32 {
 self.width * self.height
 }
 
 fn can_hold(&self, other: &Rectangle) -> bool {
 self.width > other.width && self.height > other.height
 }
}
fn main() {
 let rect1 = Rectangle {
 width: 30,
 height: 50,
 };
 
 println!("Area: {}", rect1.area());
}

Associated Functions #

Functions that don’t take self as a parameter:

impl Rectangle {
 fn square(size: u32) -> Rectangle {
 Rectangle {
 width: size,
 height: size,
 }
 }
}
fn main() {
 let sq = Rectangle::square(3);
}

Related

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /