Hi,
in the function below:
pub fn a(a: Vec<u8>) -> Result<u8, Vec<u8>> {
let x = a.get(8).ok_or(a.clone())?;
Ok(*x)
}
I need to clone a
or the compiler will complain.
Instead I could do:
pub fn b(a: Vec<u8>) -> Result<u8, Vec<u8>> {
let x = a.get(8);
match x {
Some(z) => Ok(*z),
None => Err(a),
}
}
I'm wondering which is the best method?
The method 1 generate more code (Compiler Explorer) but it actually clone only in the cold path. Method 1 simplify a lot the code if a function can fail in several point and if fail cases are nested.
I'm also wondering if I'm missing something and there is a third way to early return error without boilerplate and without cloning in situations like the one above.
Ty