I want to have a function that let me extract infos from Results. The problem is what to return if something fails (the function uses a generic parameter). Here is my code:
fn check<T, E>(x: Result<T, E>) -> T {
if let Ok(sk) = x {
return sk;
} else {
println!("uh oh");
return 0 as T;
}
}
As you can guess it doesn't work, what should i put instead of 0 as T
?
If you want to return the default value for the type (0 for numbers, false
for bools, an empty string for strings etc.) you can constrain it to T: Default
and return T::default()
:
fn check<T: Default, E>(x: Result<T, E>) -> T {
if let Ok(sk) = x {
return sk;
} else {
println!("uh oh");
return T::default();
}
}
But note that there is an existing method on Result
that returns the default value in case of Err
: unwrap_or_default()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.