Skip to content

Instantly share code, notes, and snippets.

@totem3
Last active October 11, 2016 20:34
Show Gist options
  • Save totem3/a2e236188a33ecd237ba45138e11fbd3 to your computer and use it in GitHub Desktop.
Save totem3/a2e236188a33ecd237ba45138e11fbd3 to your computer and use it in GitHub Desktop.
// 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);
}
// 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