Search code examples
rusttype-conversiontraitsprimitive-typesrust-crates

How do I add a constructor to an existing primitive type?


I am trying to make primitive types and object types by adding the new method to usize:

impl usize {
    fn new(value: &u32) -> usize {
        value as usize
    }
}

I have no idea about what the message tries to say:

error[E0390]: only a single inherent implementation marked with `#[lang = "usize"]` is allowed for the `usize` primitive
 --> src/lib.rs:1:1
  |
1 | / impl usize {
2 | |     fn new(value: &u32) -> usize {
3 | |         value as usize
4 | |     }
5 | | }
  | |_^
  |
help: consider using a trait to implement these methods
 --> src/lib.rs:1:1
  |
1 | / impl usize {
2 | |     fn new(value: &u32) -> usize {
3 | |         value as usize
4 | |     }
5 | | }
  | |_^

Solution

  • You can't directly implement methods on types outside of your own crate. However, as the help message says, you can define a new trait and then implement it:

    pub trait NewFrom<T> {
        fn new(value: T) -> Self;
    }
    
    impl NewFrom<&u32> for usize {
        fn new(value: &u32) -> Self {
            *value as usize
        }
    }
    

    Still, this is a bit of an odd thing to do. Usually you would just use the built-in conversion:

    let int: u32 = 1;
    let size = int as usize;