Assume I have the following structure
struct Test {
value : i32,
}
and I implement the following method for it
impl Test {
fn take_ownership(self) -> Option<Self> {
if self.value >= 0 {
Some(self)
} else {
None
}
}
}
I am good with the consumption of the ownership in the case when value is greater than 0, but how can I rewrite the code so that the ownership is not consumed in the case None is returned?
>Solution :
You can return a Result with the failed ownership instance as the error type:
struct Test {
value : i32,
}
impl Test {
fn take_ownership(self) -> Result<i32, Self> {
if self.value >= 0 {
Ok(self.value)
} else {
Err(self)
}
}
}
Notice that this still consumes self, but you can recover it afterwards.
Also remember that you can always get an Option from a Result later on:
fn main() {
let t = Test { value: 10 };
let value = t.take_ownership().ok();
println!("{value:?}");
}