How to define impl on standard types in Rust?

Viewed 63

How can we define a wrapper type around an existing type and define functions over it?

I have tried the below code and I am getting this error

struct Deploy(u8);

impl Deploy {
    fn values_yaml(self) -> u8 {
      self+1  
    }

    fn chart(self) -> u8 {
        self+1
    }
}


fn main() {
    let a = Deploy(1);
    println!("Hello, world! {:?}", a.chart());
}

error:

error[E0369]: cannot add `{integer}` to `Deploy`
   --> src/main.rs:5:11
    |
5   |       self+1  
    |       ----^- {integer}
    |       |
    |       Deploy
    |
note: an implementation of `Add<_>` might be missing for `Deploy`

Any suggestion is most welcome.

1 Answers

You're dealing with a tuple struct, with tuple size 1. The elements of tuples are accessed via the usual syntax for tuples in Rust:

self.0

Alternatively, you can also match the fields similarly to regular tuples.

let Deploy(resource_type) = self;
Related