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?
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)
}
}
}
Playground
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:?}");
}
Playground
If you don't want to take ownership of the self object, you can try to pass and recieve it by reference:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=5f92c1ea1a69e0da1e153bd8625a5a53
impl Test {
fn take_ownership(&self) -> Option<&Self> {
if self.value >= 0 {
Some(self)
} else {
None
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With