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
For people making use of unwrap calls in the code may want to find ways how to eliminate them. Not all unwrap calls are necessary cases for errors, in particular for Option::unwrap.
The following is a short list of examples that avoid the use of unwrap while not panicking. Instead of handling both Some & None via a match statement std Rust offers some alternatives to achieve the same, in particular for iterators.
This will panic, but what we would like to return here is the number of items that match the (lowercased) world string. The filter line could be written as:
Using the rowan library assume we would like to return a list of two tokens from the parent node.
let syntax_tokens = t
.parent().unwrap().siblings_with_tokens(Direction::Next).take(2).collect::<Vec<_>>();
This fails when the given token t does not have a parent. To ignore this case we can rewrite it using the Option::into_iter function to transform the Option into an Iterator. If the Option holds a Some value the iterator executes exactly once, otherwise zero for None .
let syntax_tokens = t
.parent().into_iter().flat_map(|it| it.siblings_with_tokens(Direction::Next)).take(2).collect::<Vec<_>>();
A call to flat_map is necessary here, otherwise it returns an Iterator in a Vec (list in list).
For people making use of
unwrap
calls in the code may want to find ways how to eliminate them. Not allunwrap
calls are necessary cases for errors, in particular forOption::unwrap
.The following is a short list of examples that avoid the use of
unwrap
while not panicking. Instead of handling bothSome
&None
via amatch
statement std Rust offers some alternatives to achieve the same, in particular for iterators.This will panic, but what we would like to return here is the number of items that match the (lowercased)
world
string. Thefilter
line could be written as:Using the
rowan
library assume we would like to return a list of two tokens from the parent node.This fails when the given token
t
does not have a parent. To ignore this case we can rewrite it using theOption::into_iter
function to transform theOption
into anIterator
. If the Option holds aSome
value the iterator executes exactly once, otherwise zero forNone
.A call to
flat_map
is necessary here, otherwise it returns an Iterator in aVec
(list in list).Use
filter_map
to allow use of?
operator.rewritten as:
Closures that return an
Option
orResult
allow the?
operator. Methodfilter_map
uses anOption
as return type.The text was updated successfully, but these errors were encountered: