-
-
Save totem3/a2e236188a33ecd237ba45138e11fbd3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://play.rust-lang.org/?gist=cce473b90dd798d61725d50295026f33&version=stable&backtrace=0 | |
fn main() { | |
let vec = vec![2, 3, 4, 5]; | |
// let res: Vec<Result<i32, String>> = vec.iter() | |
let res: Result<Vec<i32>, String> = vec.iter() | |
.map(|a| if a % 2 == 0 { | |
println!("a:{}", a); | |
Ok(a * 3) | |
} else { | |
Err(format!("Error! {} is odd value!", a)) | |
}) | |
.collect(); | |
println!("{:?}", res); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://is.gd/3bSQ38 | |
fn incr(a:i32) -> i32 { a+1 } | |
fn apply<F>(t: i32, f: F) -> i32 where F: FnOnce(i32) -> i32 { | |
f(t) | |
} | |
fn main() { | |
// map can take both closure and function pointer | |
// fn map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> U | |
let f = |a:i32| a+1; | |
assert_eq!(Some(2), Some(1).map(f)); | |
assert_eq!(Some(2), Some(1).map(incr)); | |
let f = |a:i32| a+1; | |
assert_eq!(51, apply(50, f)); | |
apply(50, incr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment