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
Debugging with backtrace
1
RUST_BACKTRACE=1 cargo run
II. Grammar & Standard Library
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.
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.
use enum_iterator::IntoEnumIterator;
use int_enum::IntEnum;
#[repr(usize)]#[derive(Clone, Ord, PartialOrd, Copy, Debug, Eq, PartialEq, IntEnum, IntoEnumIterator)]pubenumResistorColor {
Black =0,
Blue =6,
Brown =1,
Green =5,
Grey =8,
Orange =3,
Red =2,
Violet =7,
White =9,
Yellow =4,
}
...
pubfncolors() -> Vec<ResistorColor> {
letmut m = ResistorColor::into_enum_iter().collect::<Vec<ResistorColor>>();
m.sort();
m
}