Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice to implement optional consuming of ownership?

Tags:

rust

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?

like image 897
Ilya Vlasov Avatar asked Dec 29 '25 13:12

Ilya Vlasov


2 Answers

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

like image 137
Netwave Avatar answered Jan 01 '26 20:01

Netwave


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
       }
    }
}
like image 45
Tamir Avatar answered Jan 01 '26 18:01

Tamir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!