Helps: rust wrap a third type to implement custom method , but allow to access it just like the origin one, include move fields

31 views Asked by At

Assume there is a third type called Car;

pub struct Car {
  name: String, 
  price: i64,
}

I need to implement some custom method, such as get the car category or validate, so I create a new type which wraps the Car.

pub struct NewCar(Car);

impl NewCar{
    fn category(&self) -> i32 {
        if self.0.name == "xxx" {
            return 1 
        }
        return 0 
    }
    
    fn validate(&self) -> bool {
        if self.0.name.is_empty() || self.0.price <= 0 {
            return false 
        }
        return true 
    }
}

but also, I want to move any of it's filed (which does not impl Copy trait) somewhere, like

let car = MyCar(car); 

let name = car.name; 
let price = car.price;

there is a Deref DerefMut trait that can allow me to access the reference of inner type field, but i can't move it's field, unless use

let car = MyCar(car); 

let name = car.0.name; 
let price = car.0.price;

here is some sample code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2da564ba9b8e395a9a5b3157cdad069d

0

There are 0 answers