You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
let pair = (0, -2);match pair {(0, y) => println!("First is `0` and `y` is `{:?}`", y),(x,0) => println!("`x` is `{:?}` and last is `0`", x),
_ => println!("It doesn't matter what they are"),}
let pair = (2, -2);match pair {(x, y)if x == y => println!("These are twins"),(x, y)if x + y == 0 => println!("Antimatter, kaboom!"),(x, _)if x % 2 == 1 => println!("The first one is odd"),
_ => println!("No correlation..."),}
fnis_odd(n:u32) -> bool{
n % 2 == 1}fnmain(){println!("Find the sum of all the squared odd numbers under 1000");let upper = 1000;// Imperative approach// Declare accumulator variableletmut acc = 0;// Iterate: 0, 1, 2, ... to infinityfor n in0.. {// Square the numberlet n_squared = n * n;if n_squared >= upper {// Break loop if exceeded the upper limitbreak;}elseifis_odd(n_squared){// Accumulate value, if it's odd
acc += n_squared;}}println!("imperative style: {}", acc);// Functional approachlet sum_of_squared_odd_numbers:u32 =
(0..).map(|n| n * n)// All natural numbers squared.take_while(|&n_squared| n_squared < upper)// Below upper limit.filter(|&n_squared| is_odd(n_squared))// That are odd.sum();// Sum themprintln!("functional style: {}", sum_of_squared_odd_numbers);}
Enums
enumCStyle{Name1,Name2,Name3,}let a = CStyle::Name1;let b = CStyle::Name1;let c = match a {CStyle::Name1 => 1,CStyle::Name2 => 2,CStyle::Name3 => 3,};
enumUnionLike{Float(f64),Int(i64),Fraction(i32,i32),NaN,}let a = UnionLike::Float(1.0);let b = UnionLike::NaN;let c = match a {Float(f) => format!("{}", f),Int(i) => format!("{}", i),Fraction(a, b) => format!("{}/{}", a, b),NaN => format!("NaN"),};assert_eq!(c,String::from("1.0"));
enumWebEvent{// An `enum` may either be `unit-like`,PageLoad,PageUnload,// like tuple structs,KeyPress(char),Paste(String),// or c-like structures.Click{x:i64,y:i64},}// A function which takes a `WebEvent` enum as an argument and// returns nothing.fninspect(event:WebEvent){match event {WebEvent::PageLoad => println!("page loaded"),WebEvent::PageUnload => println!("page unloaded"),// Destructure `c` from inside the `enum`.WebEvent::KeyPress(c) => println!("pressed '{}'.", c),WebEvent::Paste(s) => println!("pasted \"{}\".", s),// Destructure `Click` into `x` and `y`.WebEvent::Click{ x, y } => {println!("clicked at x={}, y={}.", x, y);},}}
Option, Result
enumOption<T>{Some(T),None,}let a = Some(1.0);let b = None;
fnfind(where:&[i32],what:i32) -> Option<i32>{for(index, i)in where.iter().enumerate(){if i == what {returnSome(index);}}None}assert_eq!(find(&vec![1,2,3],3),Some(2));assert_eq!(find(&vec![1,2,3],100),None);
enumResult<T,E>{Ok(T),Err(E),}let a = Ok(1.0);let b = Err("can't parse");
fnparse_strings(strs:&[&str]) -> Result<Vec<i32>,String>{letmut result = Vec::new();for i in strs {match i.parse::<i32>(){Ok(number) => result.push(number),Err(_) => returnErr(format!("can't parse string to number: {}", i)),}}Ok(result)}assert_eq!(parse_strings(&["1","2","3"]),Ok(vec![1,2,3]));assert_eq!(parse_strings(&["1","2","ы"]),Err("can't parse string to number: ы".to_string()));
Traits and implementations
structPoint{x:f64,y:f64,}implPoint{// This is a static method// Static methods don't need to be called by an instance// These methods are generally used as constructorsfnorigin() -> Point{Point{x:0.0,y:0.0}}// Another static method, taking two arguments:fnnew(x:f64,y:f64) -> Point{Point{x: x,y: y }}fnlen(&self) -> f64{(x*x + y*y).sqrt()}}let a = Point::origin();let b = Point::new(1,2);let alen = a.len();let blen = b.len();