I have a bias towards flat functions, and in ruby would normally write `return nil if condition` at the top of the method, then the rest of the non-null case after
-
Show this thread
-
I can think of like... 4? ways to write `Option -> Option` functions in rust?
1 reply 0 retweets 0 likesShow this thread -
// 1: using Option::map fn f1(opt: Option<i32>) -> Option<i32> { http://opt.map (|x| { x + 1 }) }
1 reply 0 retweets 0 likesShow this thread -
// 2: if-let fn f2(opt: Option<i32>) -> Option<i32> { if let Some(x) = opt { Some(x + 1) } else { None } }
1 reply 0 retweets 0 likesShow this thread -
// 3: match fn f3(opt: Option<i32>) -> Option<i32> { match opt { Some(x) => { Some(x + 1) } None => None, } }
1 reply 0 retweets 0 likesShow this thread -
// 4: early return using is_none() fn f4(opt: Option<i32>) -> Option<i32> { if http://opt.is _none() { return None; } Some(opt.unwrap() + 1) }
1 reply 0 retweets 0 likesShow this thread -
the linked list book uses method 1 most all the time, including cases where the closure contains side effects, which I find... unnerving I have been rewriting to method 2 a fair bit, but the additional verbosity (doing the unwrapping and re-wrapping explicitly) tedious
1 reply 0 retweets 0 likesShow this thread -
method 4 is closest to what I'd write in ruby/js, but feels extremely un-rust-like for some reason, plus you still need to wrap Some() around the result
4 replies 0 retweets 0 likesShow this thread -
here's a function where method 2 feels like the right thing; the None case actually does something interestingpic.twitter.com/7FdCM4P69q
1 reply 0 retweets 0 likesShow this thread -
you can use ?, so, another method: // 5: ? fn f2(opt: Option<i32>) -> Option<i32> { let x = opt?; Some(x + 1) } so what are the rules for which types work with `?`? is there a trait involved?
2 replies 0 retweets 0 likesShow this thread
The Try trait https://doc.rust-lang.org/std/ops/trait.Try.html …
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.