A struct, or structure, is a custom data type that lets you package together and name multiple related values that make up a meaningful group. Structs are similar to tuples in that both hold multiple related values, but unlike tuples, in a struct, you’ll name each piece of data so it’s clear what the values mean.
To define a struct, we enter the keyword struct
and name the entire struct. A struct’s name should describe the significance of the pieces of data being grouped. Here is an example :
struct Color {
red: u8,
green: u8,
blue: u8,
}
To use a struct after we’ve defined it, we create an instance of that struct by specifying concrete values for each of the fields. We make an instance by stating the name of the struct
and then add curly brackets containing key: value pairs, where the keys are the names of the fields and the values are the data we want to store in those fields. Using the struct
above, here is an example of an instance:
struct Color {
red: u8,
green: u8,
blue: u8,
}
fn main() {
let black = Color {
red: 0,
blue: 0,
green: 0,
};
println!("Black = rgb({}, {}, {})", black.red, black.green, black.blue);
}
Tuple Structs
Rust supports tuple structs, which are similar to regular structs but use unnamed fields.
struct Point(i32,i32,i32);
fn main() {
let origin = Point(0, 0, 0);
println!("Origin point: ({}, {}, {})", origin.0, origin.1, origin.2);
}
Unit-Like Structs
Rust also has unit-like structs, which are useful when you need to implement a trait on some type but don’t need to store any data in it.
struct Subject;
fn main() {
let math = Subject;
}
Top comments (0)