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
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
Ownership is a bit complicated with structs
https://play.rust-lang.org/?gist=e74541b3fc609dfce49ad2aff13ba11a&version=stable
A struct owns all of its fields individually
Moving a field out of a struct makes it "partially moved"
References stored in structs need to outlast the struct
Normally need to explicitly specify reference lifetime
impl
Mechanism for getting that fancy OO-style syntax
Implementor defines whether self argument is by move, reference or mut reference
https://play.rust-lang.org/?gist=ad54d7fbac5010d57a787357aa5d96e2&version=stable
Allows chaining of operators, which can be syntactically nice
Deriving
Mechanism for getting traits defined automatically for your struct
Uses attribute syntax
Common kind of thing to write
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] struct Temperature(i64);
https://play.rust-lang.org/?gist=bca2d7bc4b303ff3d5331b0bc476aeef&version=stable
Pattern Matching
Not specific to structs / enums
Mechanism for deconstructing a composite thing
https://play.rust-lang.org/?gist=27543ca8dcac3e9062949db610b97190&version=nightly
We've seen some of this before.
Two kinds: "refutable" and "irrefutable"
let
requires irrefutable patternmatch
allows refutable pattern, but all possible patterns must be matched
Match
The
match
statement is the canonical pattern matching toolhttps://play.rust-lang.org/?gist=c18cf7385e82e70eeb75fbdd5ff5dfc5&version=stable
Note the existence of
..
,...
,|
(not shown, only at top level),@
First match is chosen
Compiler checks that every possible value will be matched, and that later matches are not subsumed by earlier
Pattern Variable Modifiers
Rules for move/borrow are the same for pattern variables
For convenience, you can modify a pattern variable with
ref
orref 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