Struct

Classic Struct

struct ColorClassicStruct {
    red: u8,
    green: u8,
    blue: u8,
}
 
fn classic_c_structs() {
    let green = ColorClassicStruct {
        red: 0,
        green: 255,
        blue: 0,
	};
}

Tuple Like Struct

struct ColorTupleStruct(u8, u8, u8);
 
fn tuple_structs() {
    let green = ColorTupleStruct(0, 255, 255);
 
    assert_eq!(green.0, 0);
    assert_eq!(green.1, 255);
    assert_eq!(green.2, 0);
}

Unit Like Struct

struct UnitStruct;
fn unit_structs() {
	let unit_struct = UnitStruct;
	let message = format!("{:?}s are fun!", unit_struct);
	assert_eq!(message, "UnitStructs are fun!");
}

Struct Update Syntax

like JavaScript’s fill
Make sure you put the .. at the end of the struct.

struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}
 
fn main() {
    // --snip--
 
    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
    };
}

impl struct

  • define methods and associated functions for that struct.
struct Lexer {
    tokens: Vec<Token>,
}
impl Lexer {
    fn new(input: &str) -> Lexer {
        let mut tokens = input
            .chars()
            .filter(|it| !it.is_ascii_whitespace())
            .map(|c| match c {
                '0'..='9' |
                'a'..='z' | 'A'..='Z' => Token::Atom(c),
                _ => Token::Op(c),
            })
            .collect::<Vec<_>>();
        tokens.reverse();
        Lexer { tokens }
    }
    fn next(&mut self) -> Token {
        self.tokens.pop().unwrap_or(Token::Eof)
    }
    fn peek(&mut self) -> Token {
        self.tokens.last().copied().unwrap_or(Token::Eof)
    }
}