A struct is a simple Rust data structure that can be defined and customised by the programmer.
Structs are made up of fields, internal pieces of data that also need their own data types:
struct Train {
colour: String, // Field definitions are separated by commas
num_of_coaches: i32,
max_speed_kmh: f64
}
fn main() {
let t = Train {
colour: String::from("Green"),
num_of_coaches: 12,
max_speed_kmh: 109.125
};
}
Like with variables, each struct, and each field, also needs its own alias.
Struct fields can also be other structs:
struct Driver {
name: String,
years_of_exp: i32,
can_drive_diesel_trains: bool
}
struct Train {
driver: Driver, // A driver assigned to a train
colour: String,
num_of_coaches: i32,
max_speed_kmh: f64
}
fn main() {
let d = Driver {
name: String::from("Dave"),
years_of_exp: 5,
can_drive_diesel_trains: false
};
let new_t = Train {
driver: d,
colour: String::from("Red"),
num_of_coaches: 5,
max_speed_kmh: 149.55
};
}
Exercise:
Try adding a field of type char with the alias "character" to the struct defined below, before printing it:
Enums, short for enumerations, are tiny pieces of data that, similar to structs, are defined entirely by the programmer as a custom data structure, and can only be one of multiple variants (sometimes called discriminants):
enum Reviews {
Excellent,
Great,
Good,
Okay,
Bad,
Terrible
}
fn main() {
let bad_review = Reviews::Bad;
}
Enums can have their own variants defined inline as custom data types (like with the above example). Variants with an alias but with no value are said to be of the unit type.
In a similar way to structs, enums can have multiple fields of different types and data structures:
enum OpcodeInts {
RRQ = 1, // Variants can represent hardcoded values...
WRQ = 2,
DATA = 3,
ACK = 4,
ERR = 5
}
enum Lengths {
One(i32), // ...tuples of different lengths...
Two(i32, i32),
Three(i32, i32, i32),
Four(i32, i32, i32, i32),
Five(i32, i32, i32, i32, i32)
}
enum Structs {
Point {x: i32, y: i32}, // ...and structs!
Precise3DPoint {x: f32, y: f32, z: f32},
}
enum Mix {
Tuple(f64, f64), // Enums can mix these types together as well
Vehicle {colour: String, num_of_wheels: i32}
}
fn main() {
let opcode = OpcodeInts::DATA;
let three_d_point = Structs::Precise3DPoint {
x: 28.17,
y: 34.78,
z: 97.12
};
let tuple_example = Mix::Tuple(54.982, 34.195);
}
Exercise:
Try adding a tuple variant of length 6 with the alias "Types", and six different data types within, to the enum defined below: