How do I return a custom error from Vec
binary search when the item is not present?
let who = ["account 1", "account 2", "account 3", "account 4", "account 5", "account 6"];
let insert = who.binary_search(&who).err().ok_or(Error::<T>::AlreadyVetoed)?;
error message
cannot use the `?` operator in a method that returns `()`
alice
January 11, 2022, 4:45pm
2
You can't return an error in a function that doesn't have a Result
as its return value.
The function you've linked to returns DispatchResult
, which is defined here as std::result::Result<(), DispatchError>
.
1 Like
tuffy
January 11, 2022, 5:30pm
5
Slice's binary search returns a Result<usize, usize>
with the error being where in the slice a new entry might fit. So wouldn't it be possible to use Result::map_err to transform it into your desired custom error?
1 Like
kornel
January 12, 2022, 1:29am
6
Are you sure it's the right code? The error message you've quoted doesn't seem to apply to the code you've linked to.
Check if you don't have the code inside a closure. That's a common source of this error, e.g.:
fn fallible(…) -> Result<…> {
foo.map(|x| bar(x)?);
…
}
won't work, even if foo
is in a function returning result, because the bar
call is in a closure that has its own return type.
2 Likes
system
Closed
April 12, 2022, 1:29am
7
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.