Reputation: 247
fn pair_finder(pairs_length: u64) {
let mut path: HashMap<u64, u64> = HashMap::new();
for i in 0..pairs_length {
if (metadata.token0 == pair_metadata.token0)
|| (metadata.token0 == pair_metadata.token1)
|| (i == *path.get(¤t_depth).unwrap())
{
continue;
}
}
}
I have a function which includes the above block. Path is a HashMap
where first u64
is ID of path and second u64
is pair ID. current_depth
used is the part of loop where it increases after something new to path is added.
However it panicked. It is because I used the i == *path.get(¤t_depth).unwrap()
in the if block. And HashMap
is empty at current_depth
and it got a None
value. Are there any way to prevent panic on None
and consider that block of if as false
?
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:69:52
Upvotes: 2
Views: 516
Reputation: 229
Option<T>
implements Eq
whenever T
implements Eq
. This means that you can directly compare variants of the Option
type, like this:
assert!(Some(1) == Some(1));
assert!(None::<i32> == None);
assert!(Some(1) != Some(2));
assert!(Some(1) != None);
So instead of writing this, which panics if maybe_v
is the None
variant:
maybe_v.unwrap() == a
You could write this, which just evaluates to false
if maybe_v
is the None
variant:
maybe_v == Some(a)
So in your case, you can write:
fn pair_finder(pairs_length: u64) {
let mut path: HashMap<u64, u64> = HashMap::new();
for i in 0..pairs_length {
if (metadata.token0 == pair_metadata.token0)
|| (metadata.token0 == pair_metadata.token1)
|| (Some(&i) == path.get(¤t_depth))
{
continue;
}
}
}
Upvotes: 7