Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
       }
    }
}

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading