Introduction
In this lab, we will be exploring structures in the Rust programming language. There are three types of structures ("structs") that can be created using the struct
keyword: tuple structs, classic C structs, and unit structs. Tuple structs are essentially named tuples, C structs are the traditional structs found in C programming, and unit structs are field-less and useful for generics. We can define structs with multiple fields, such as Person
which has name
and age
fields. Structs can also be reused as fields of another struct, as shown in the example of a Rectangle
which consists of two Point
structs representing the top left and bottom right corners. We can initialize structs using field init shorthand and access their fields using dot notation. It is also possible to destructure structs using the let
binding. Additionally, the lab provides two activities - creating a function rect_area
to calculate the area of a Rectangle
using nested destructuring, and creating a function square
that takes a Point
and a f32
as arguments and returns a Rectangle
with its top left corner on the point and a width and height corresponding to the f32
.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use
main.rs
, compile and run it withrustc main.rs && ./main
.