Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Create simple struct

  • struct

  • A simple struct will have one or more fields. Each field has a name and a type.

  • We can then create an instance of the struct with actual values.

  • We can use the dot-notation to access the values of the fields.

  • We cannot change the values unless we declare the struct as mutable using the mut keyword.

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let a = Point { x: 2, y: 3 };
    println!("{}", a.x);
    println!("{}", a.y);

    // a.y = 7;
    // cannot assign to `a.y`, as `a` is not declared as mutable
    // println!("{}", a.y);
}
2
3