Structures

There are three types of structures (“structs”) that can be created using the
struct keyword:

  • Tuple structs, which are, basically, named tuples.
  • The classic C structs
  • Unit structs, which are field-less, are useful for generics.
  1. #[derive(Debug)]
  2. struct Person<'a> {
  3. name: &'a str,
  4. age: u8,
  5. }
  6. // A unit struct
  7. struct Nil;
  8. // A tuple struct
  9. struct Pair(i32, f32);
  10. // A struct with two fields
  11. struct Point {
  12. x: f32,
  13. y: f32,
  14. }
  15. // Structs can be reused as fields of another struct
  16. #[allow(dead_code)]
  17. struct Rectangle {
  18. p1: Point,
  19. p2: Point,
  20. }
  21. fn main() {
  22. // Create struct with field init shorthand
  23. let name = "Peter";
  24. let age = 27;
  25. let peter = Person { name, age };
  26. // Print debug struct
  27. println!("{:?}", peter);
  28. // Instantiate a `Point`
  29. let point: Point = Point { x: 0.3, y: 0.4 };
  30. // Access the fields of the point
  31. println!("point coordinates: ({}, {})", point.x, point.y);
  32. // Make a new point by using struct update syntax to use the fields of our other one
  33. let new_point = Point { x: 0.1, ..point };
  34. // `new_point.y` will be the same as `point.y` because we used that field from `point`
  35. println!("second point: ({}, {})", new_point.x, new_point.y);
  36. // Destructure the point using a `let` binding
  37. let Point { x: my_x, y: my_y } = point;
  38. let _rectangle = Rectangle {
  39. // struct instantiation is an expression too
  40. p1: Point { x: my_y, y: my_x },
  41. p2: point,
  42. };
  43. // Instantiate a unit struct
  44. let _nil = Nil;
  45. // Instantiate a tuple struct
  46. let pair = Pair(1, 0.1);
  47. // Access the fields of a tuple struct
  48. println!("pair contains {:?} and {:?}", pair.0, pair.1);
  49. // Destructure a tuple struct
  50. let Pair(integer, decimal) = pair;
  51. println!("pair contains {:?} and {:?}", integer, decimal);
  52. }

Activity

  1. Add a function rect_area which calculates the area of a rectangle (try
    using nested destructuring).
  2. Add a function square which takes a Point and a f32 as arguments, and returns a Rectangle with its lower left corner on the point, and a width and height corresponding to the f32.

See also:

attributes and destructuring