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. }

7. // A unit struct
8. struct Nil;

10. // A tuple struct
11. struct Pair(i32, f32);

13. // A struct with two fields
14. struct Point {
15. x: f32,
16. y: f32,
17. }

19. // Structs can be reused as fields of another struct
20. #[allow(dead_code)]
21. struct Rectangle {
22. p1: Point,
23. p2: Point,
24. }

26. fn main() {
27. // Create struct with field init shorthand
28. let name = "Peter";
29. let age = 27;
30. let peter = Person { name, age };

32. // Print debug struct
33. println!("{:?}", peter);

36. // Instantiate a `Point`
37. let point: Point = Point { x: 0.3, y: 0.4 };

39. // Access the fields of the point
40. println!("point coordinates: ({}, {})", point.x, point.y);

42. // Make a new point by using struct update syntax to use the fields of our other one
43. let new_point = Point { x: 0.1, ..point };
44. // `new_point.y` will be the same as `point.y` because we used that field from `point`
45. println!("second point: ({}, {})", new_point.x, new_point.y);

47. // Destructure the point using a `let` binding
48. let Point { x: my_x, y: my_y } = point;

50. let _rectangle = Rectangle {
51. // struct instantiation is an expression too
52. p1: Point { x: my_y, y: my_x },
53. p2: point,
54. };

56. // Instantiate a unit struct
57. let _nil = Nil;

59. // Instantiate a tuple struct
60. let pair = Pair(1, 0.1);

62. // Access the fields of a tuple struct
63. println!("pair contains {:?} and {:?}", pair.0, pair.1);

65. // Destructure a tuple struct
66. let Pair(integer, decimal) = pair;

68. println!("pair contains {:?} and {:?}", integer, decimal);
69. }

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