Skip to content

Rust Structs

Overview

Structs are custom data types that let you bundle related values together.

🏗️ Defining Structs

rust
struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };

    println!("User: {}", user1.username);
}

🔧 Methods

rust
impl User {
    fn new(email: String, username: String) -> User {
        User {
            email,
            username,
            active: true,
            sign_in_count: 1,
        }
    }

    fn is_active(&self) -> bool {
        self.active
    }
}

Continue learning: Next Chapter - Rust Enums

Content is for learning and research only.