Structs in Rust

Structs

Structs in Rust are typed collections of fields. They’re useful for grouping data together to form records.

This Person struct type has name and age fields.

struct Person {
    name: String,
    age: u32,
}

new_person constructs a new Person struct with the given name.

fn new_person(name: String) -> Person {
    let p = Person { name, age: 42 };
    p
}

This syntax creates a new struct.

fn main() {
    println!("{:?}", Person { name: "Bob".to_string(), age: 20 });
}

You can name the fields when initializing a struct.

fn main() {
    println!("{:?}", Person { name: "Alice".to_string(), age: 30 });
}

Omitted fields will be zero-valued.

fn main() {
    println!("{:?}", Person { name: "Fred".to_string(), age: 0 });
}

It’s idiomatic to encapsulate new struct creation in constructor functions.

fn main() {
    println!("{:?}", new_person("Jon".to_string()));
}

Access struct fields with a dot.

fn main() {
    let s = Person { name: "Sean".to_string(), age: 50 };
    println!("{}", s.name);
}

Structs are mutable.

fn main() {
    let mut sp = Person { name: "Sean".to_string(), age: 50 };
    sp.age = 51;
    println!("{}", sp.age);
}

If a struct type is only used for a single value, we don’t have to give it a name. The value can have an anonymous struct type. This technique is commonly used for testing.

fn main() {
    let dog = struct {
        name: String,
        is_good: bool,
    } {
        name: "Rex".to_string(),
        is_good: true,
    };
    println!("{:?}", dog);
}

Now that we can run and build basic Rust programs, let’s learn more about the language.