Integer types:
fn main() {
println!("{}", fac(6));
}
fn fac(n: usize) -> f64 {
let mut acc = 1;
for i in 1..=n {
acc *= i;
}
acc as _
}
// usize (64-bit u64) (32-bit u32)
// unsigned integers: u8 u16 u32 u64 u128
// isize (64-bit i64) (32-bit i32)
// signed integers: i8 i16 i32 i64 i128
// floats: f32 f64
Reading from the console, introducing unwrap():
use std::io::{BufRead, stdin};
fn main() {
let stdin = stdin();
let mut lines = stdin.lock().lines();
// if the first line isn't a number, then defaults to 0
let in1 : isize = lines.next().unwrap().unwrap().parse().unwrap_or(0);
// will panic when parsing the second line if it isn't a number
let in2 : isize = lines.next().unwrap().unwrap().parse().unwrap();
println!("sum: {}", in1 + in2);
}
// how does unwrap work? this is what Result really looks like
enum MyResult<T,E> {
Ok(T),
Err(E),
}
impl<T,E> MyResult<T,E> {
fn unwrap(self) -> T {
match self {
MyResult::Ok(t) => t,
MyResult::Err(_) => panic!("there was an error"),
}
}
}
// therefore, any unwrap() can be rewritten as a match statement
// there are plenty of methods on Result and Option for supplying default
// params, and converting from Result -> Option or Option -> Result