GGistDev

Structs in Rust

Structs group related fields into custom data types. Implement behavior with impl blocks and derive common traits.

Declaring structs

Named and tuple structs.

struct User { id: u64, name: String }
struct Pair(i32, i32);

Instantiation and update syntax

let u = User { id: 1, name: String::from("Ada") };
let u2 = User { name: String::from("Guido"), ..u };

..u moves remaining fields (unless they implement Copy).

Field init shorthand and ownership

let name = String::from("Ada");
let u = User { id: 1, name }; // name moved into struct

Methods and associated functions

impl User {
    fn new(id: u64, name: impl Into<String>) -> Self {
        Self { id, name: name.into() }
    }
    fn greet(&self) -> String { format!("Hi {}", self.name) }
}

Deriving common traits

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]

#[derive(Debug, Default)]
struct Point { x: i32, y: i32 }

Struct update and ownership caveats

After using ..u, moved fields cannot be accessed.

Lifetimes in structs (with references)

Structs holding references must declare lifetimes (see Lifetimes section).

Summary

  • Use named/tuple structs; init with field shorthand and update syntax
  • Implement behavior with impl; derive common traits for ergonomics