Structs and Related Concepts

Rust struct

  • Seen a bunch of these already

  • Basic idea is the same as structures in any language

  • Rust structs are fancy, and an essential building block

  • Most of the standard API is built out of struct, enum, trait


  • Basic decl syntax is straightforward

      struct Point {
          x: i64,
          y: i64,
  • There is no default constructor: can create with again-obvious syntax

      let p = Point{ x: 5, y: -2 };

Fancy Features

  • Common case of tag-name = varname is special

      let x = 5;
      let p = Point{ x, y: -2 };
  • Can have empty structures: these are inhabited by only one value

  • "Tuple structs" have anonymous fields

      struct Point(int64, int64);
      let p = Point(3, 2);
      let x = p.0;
  • Single-element tuple structs are often used for "newtyping"

      struct Temperature(int64);

Ownership and Lifetimes



Pattern Matching


Pattern Variable Modifiers

  • Rules for move/borrow are the same for pattern variables

  • For convenience, you can modify a pattern variable with ref or ref mut to have it borrowed instead of moved


  • Struct layout concepts are in the book: not too important

  • Need to master structs: they are used everywhere


Last modified: Tuesday, 24 April 2018, 6:02 PM