structs are a way to create your own data types (like in C).

struct Point {
	x: i32,
	y: i32,
}
 
fn main() {
	let origin = Point { x: 0, y: 0 };
 
	println!("The origin is at ({}, {})", origin.x, origin.y);
}

naming convention for structs are starting with a capital letter and camel-cased.

like any variable binding, structs are immutable by default; unless you give them a mut in their binding.

Initialization of a data structure (struct, enum, union) can be simplified when fields of the data structure are initialized with variables of the same names as the fields.

#[derive(Debug)]
struct Person<'a> {
    name: &'a str,
    age: u8
}
 
fn main() {
    // Create struct with field init shorthand
    let name = "Peter";
    let age = 27;
    let peter = Person { name, age };
 
    // Debug-print struct
    println!("{:?}", peter);
}
 

Update syntax


you can also use the same type of copy syntax that you can do with Python and javascript

struct Point3d {
    x: i32,
    y: i32,
    z: i32,
}
 
let mut point = Point3d { x: 0, y: 0, z: 0 };
point = Point3d { y: 1, .. point };
 
let origin = Point3D {x: 0, y: 0, z: 0};
let new_point = Point3D {x: 5, .. origin};

you can also see on the last couple lines is that you can use this for new or existing structs or with different structs

this .. syntax will copy over origin’s y and z value.

also if you do this:

#[derive(Debug)]
struct Box {
	x: i32,
	y: i32
}
 
 
let box1 = Box {x: 5, y: 8};
 
let box2 = Box {x: 8, ..box1};
 
// what do you think box2 will output?

Tuple-like Structs


tuple structs are like normal structs but they don’t have named values.

struct Point(i32, i32, i32);
struct Color(i32, i32, i32);
 
let colorscheme = Color(154, 255, 15);
 
let red = colorscheme.0 // grabs 154
 
// destructuring let
let Point(_, green, blue) = colorscheme;

you can also use tuple structs to create a “newtype” pattern.

struct Rating(i32);
 
let movie_rating = Rating(5);
 
let Rating(ghostbusters_review) = movie_rating;
 
println!("review for ghostbusters: {}", ghostbusters_review);

creates your own “type” that lets you give more meaning to a variable.

Match