blog.dopana

Back

Seventh post in the basic Rust series. Structs let you group related values into a single custom data type to model structured concepts in your programs.

Defining and instantiating structs#

A classic struct has named fields:

If field names match variable names in scope, you can use field init shorthand:

fn build_user(email: String, username: String) -> User {
    User {
        active: true,
        username,
        email,
        sign_in_count: 1,
    }
}
rust

Struct update syntax#

Create a new instance using values from an existing instance with ..:

let user2 = User {
    email: String::from("bob@example.com"),
    ..user1
};
rust

Note that field values with move semantics (like username in user1) will be moved into user2.

Tuple structs and unit-like structs#

Tuple structs have unnamed fields, identified by position:

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
rust

Unit-like structs have no fields at all and are useful when implementing traits without holding state:

struct AlwaysEqual;
let subject = AlwaysEqual;
rust

Methods and impl blocks#

Define methods on a struct inside an impl block. The first parameter is usually &self (to borrow), &mut self (to mutate), or self (to take ownership):

Conclusion#

Structs allow you to create domain-specific types with named fields or tuple positions, and impl blocks organize behaviors alongside data. Next in this series: enums and pattern matching.

References#