Lei Zhilong

The best way to input is to output

Jun 4, 2020 - 3 minute read - Comments - Cheat Sheets

Rust

Disclaimer: This article will be updated from time to time to add new content or make any changes in exsisting sections without any notice. Using them under your own investigation in production is advised.

I. Building

  1. Debugging with backtrace
1
RUST_BACKTRACE=1 cargo run

II. Grammar & Standard Library

  1. use unwarp and expect to handle Result<T>
1
let f = File::open("hello.txt").unwrap();

Instead of using match explictly to handle Result<T>, unwrap will return T on OK or call panic() for us on Err

1
let f = File::open("hello.txt").expect("Fail to open file hello.txt");

More conveniently, rust provides us with expect that not only act the same as unwrap in Result<T> handling but also allow us to customize error message.

  1. use ‘map’ and ‘map_err’ to convert Result<U, E>
  • map: Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched. This function can be used to compose the results of two functions.
1
2
3
4
5
6
7
8
let line = "1\n2\n3\n4\n";

for num in line.lines() {
    match num.parse::<i32>().map(|i| i * 2) {
        Ok(n) => println!("{}", n),
        Err(..) => {}
    }
}
  • map_err: Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched. This function can be used to pass through a successful result while handling an error.
1
2
3
4
5
6
7
fn stringify(x: u32) -> String { format!("error code: {}", x) }

let x: Result<u32, u32> = Ok(2);
assert_eq!(x.map_err(stringify), Ok(2));

let x: Result<u32, u32> = Err(13);
assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
  1. match a rang of integers
1
2
3
4
5
6
match speed {
    x @ 1..=4 => x as f64 * 221.0,
    x @ 5..=8 => x as f64 * 221.0 * 0.9,
    x @ 9..=10 => x as f64 * 221.0 * 0.77,
    _ => 0.0 as f64,
}

III. Third-Party Librarys

  1. use IntEnum to associate enum with a numberical value
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

use enum_iterator::IntoEnumIterator;
use int_enum::IntEnum;

#[repr(usize)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, IntEnum)]
pub enum ResistorColor {
    Black = 0,
    Blue = 6,
    Brown = 1,
    Green = 5,
    Grey = 8,
    Orange = 3,
    Red = 2,
    Violet = 7,
    White = 9,
    Yellow = 4,
}

pub fn color_to_value(_color: ResistorColor) -> usize {
    _color.int_value()
}

pub fn value_to_color_string(value: usize) -> String {
    match ResistorColor::from_int(value) {
        Ok(v) => format!("{:?}", v),
        Err(_) => String::from("value out of range"),
    }
}

...
  1. use IntoEnumIterator to iterate enum values
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use enum_iterator::IntoEnumIterator;
use int_enum::IntEnum;

#[repr(usize)]
#[derive(Clone, Ord, PartialOrd, Copy, Debug, Eq, PartialEq, IntEnum, IntoEnumIterator)]
pub enum ResistorColor {
    Black = 0,
    Blue = 6,
    Brown = 1,
    Green = 5,
    Grey = 8,
    Orange = 3,
    Red = 2,
    Violet = 7,
    White = 9,
    Yellow = 4,
}

...

pub fn colors() -> Vec<ResistorColor> {
    let mut m = ResistorColor::into_enum_iter().collect::<Vec<ResistorColor>>();
    m.sort();
    m
}