Structs

View saved

Define and create a struct

Name fields and types. Construct with struct literal syntax.

struct User {
    name: String,
    active: bool,
}

fn main() {
    let u = User {
        name: String::from("Ada"),
        active: true,
    };
    println!("{} {}", u.name, u.active);
}

Update with mut

Mark the binding mutable to change fields.

let mut u = User { name: String::from("Ada"), active: true };
u.active = false;

Implement methods

Put methods in an impl block. &self borrows the instance.

impl User {
    fn label(&self) -> String {
        format!("{} ({})", self.name, self.active)
    }
}

Struct tips

  • Tuple structs exist for simple wrappers
  • Unit-like structs have no fields
  • Derive Debug to print with {:?}
  • Ownership still applies to each field

Comments

One comment per signed-in account. Comments are saved with this page’s URL.