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

Viewed 176

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?

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

Related