Skip to content

Latest commit

 

History

History
293 lines (227 loc) · 3.38 KB

DERIVE.md

File metadata and controls

293 lines (227 loc) · 3.38 KB

Summary of Appendix C from the book

These are the standard traits we can #[derive(NameOfTheTrait)]

Trait

Requires

Useful for

Usage example

Clone deep-copying objects
#[derive(Clone)]
struct MyData {
    v: Vec<u32>,
    s: String,
}

let obj = MyData { v: vec![1,2,3], s: "abcd".into() };

// this now works; duplicate is a deep copy
let duplicate = obj.clone();
Copy Clone automatic bit-copying objects, instead of moving
#[derive(Copy, Clone)]
struct Point {
    x: f32,
    y: f32,
}

let p = Point { x: 0.3, y: 0.67 };

// this now works; p2 is a copy, p was not moved
let p2 = p;
println!("{} {}", p, p2);
Debug debug-printing objects
#[derive(Debug)]
struct Point {
    x: f32,
    y: f32,
}

let p = Point { x: 0.3, y: 0.67 };

// this now works; notice the {:?} debug-format
// prints "Point { x: 0.3, y: 0.67 }"
println!("{:?}", p);
PartialEq deep-comparing objects with `==`
#[derive(PartialEq)]
struct MyData {
    v: Vec<u32>,
    s: String,
}

let a = MyData { v: vec![1,2,3], s: "abcd".into() };
let b = MyData { v: vec![1,2,3], s: "xyzw".into() };

// this now works; prints "false"
println!("{}", a == b);
Eq PartialEq marks equality as transitive (total)
required when using types in a HashSet or as keys in a HashMap

see HashSet example below

PartialOrd PartialEq deep-comparing comparing objects with `<`, `<=`, `>=` and `>`
#[derive(PartialOrd)]
struct MyData {
    v: Vec<u32>,
    s: String,
}

let a = MyData { v: vec![1,2,3], s: "abcd".into() };
let b = MyData { v: vec![1,2,3], s: "xyzw".into() };

// this now works; prints "true"
println!("{}", a < b);
Ord PartialOrd marks ordering as transitive (total)
required when using types in a BTreeSet or as keys in a BTreeMap

see BTreeSet example below

Hash getting the hash of an object
required when using types in a HashSet or as keys in a HashMap

see HashSet example below

Default constructing an object in a basic, "default" state
#[derive(Default)]
struct MyData {
    v: Vec<u32>,
    s: String,
}

// this now works; v is an empty Vec, and s is an empty String
let a = MyData::default();

// alternative way to write
let b: MyData = Default::default();

HashSet usage

#[derive(Hash, Eq, PartialEq)]
struct MyData {
    v: Vec<u32>,
    s: String,
}

use std::collections::HashSet;

// this now works
let mut set: HashSet<MyData> = HashSet::new();

BTreeSet usage

#[derive(Eq, PartialEq, Ord, PartialOrd)]
struct MyData {
    v: Vec<u32>,
    s: String,
}

use std::collections::BTreeSet;

// this now works
let mut set: BTreeSet<MyData> = BTreeSet::new();