Skip to content

Latest commit

 

History

History
68 lines (57 loc) · 1.28 KB

File metadata and controls

68 lines (57 loc) · 1.28 KB

Notes

Takeaways

There are three types of structs:

  • Tuple structs, which are, basically, named tuples.
struct Pair(i32, f32);
struct Point {
    x: f32,
    y: f32
}
  • Unit structs, which are field-less, useful for generics.
struct Unit;

Struct instantiation can be used as an expression.

struct Point {
    x: f32,
    y: f32
}
struct Rectangle {
    top_left: Point,
    bottom_right: Point
}
let rect = Rectangle { 
    top_left: Point { x: 10.3, y: 0.4 },
    bottom_right: Point { x: 10.3, y: 0.4 }
};

Destructuring

Structs can be destructured using a let binding:

  • Structs that have named fields
struct Point {
    x: f32,
    y: f32
}
// Instantiation of a `Point` to use for destructuring
let point: Point = Point { x: 10.3, y: 0.4 };
// Destructre a struct
let Point { x: x2, y: y2 } = point;
  • Tuple structs (work like normal tuples)
// Instantitate a tuple struct
let pair = Pair(1, 0.1);
// Destructure a tuple struct
let Pair(integer, decimal) = pair;

They both use the same way you would to instantiate the struct.

Note

Nested destructuring is also supported.

Questions