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

Basics

  • 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

    https://play.rust-lang.org/?gist=c4f53c4e833a2e8b9f624440c9e3b7fe&version=stable

  • "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

impl

Deriving

Pattern Matching

Match

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

Misc

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

  • Need to master structs: they are used everywhere

Coding

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