Basics

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}
 
fn build_user(email: String, username: String) -> User {
    // When struct field name and parameter name are the same shorthand syntax can be used
    User {
        email,
        username,
        active: true,
        sign_in_count: 1,
    }
}
 
fn print_data(user: User) {
    println!("User email is: {}", user.email);
    println!("User username is: {}", user.username);
    println!("User sign in count is: {}", user.sign_in_count);
    println!("User active is: {}", user.active);
}
 
fn main() {
    let user1 = build_user(
        String::from("[email protected]"),
        String::from("someusername123"),
    );
 
    println!("User 1");
    print_data(user1);
 
    let mut user2 = User {
        email: String::from("[email protected]"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };
    user2.email = String::from("[email protected]");
 
    println!("User 2");
    print_data(user2);
}
 

Tuple Struct

fn main() {
    struct Color(i32, i32, i32);
    struct Point(i32, i32, i32);
 
    let black = Color(0, 0, 0);
    let origin = Point(0, 0, 0);
}

Debug trait

To print out debugging information we have the debug trait:

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
 
fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
 
    println!("rect1 is {:?}", rect1);
}

Methods

Methods are like functions, but for structs:

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
 
impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}
 
fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
 
    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}

Associated Functions

These are Rust’s take on static functions. They don’t take self as a parameter

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
 
impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
    fn square(size: u32) -> Rectangle {
        Rectangle {
            width: size,
            height: size,
        }
    }
}
 
fn main() {
    let rect1 = Rectangle::square(10);
    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}