3

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 | | }
  | |_^
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
khanh
  • 600
  • 5
  • 20
  • See also [How to idiomatically convert between u32 and usize?](https://stackoverflow.com/q/43704758/155423); [What's the difference between `usize` and `u32`?](https://stackoverflow.com/q/29592256/155423); [Why is type conversion from u64 to usize allowed using `as` but not `From`?](https://stackoverflow.com/q/47786322/155423); [How do I convert a usize to a u32 using TryFrom?](https://stackoverflow.com/q/50437732/155423). – Shepmaster Feb 27 '19 at 17:08
  • 1
    This looks like a [XY question](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What's the real goal ? Aren't you looking for type aliasing instead ? – Denys Séguret Feb 27 '19 at 17:11
  • @DenysSéguret My real goal is **usize::new()** returns an usize number from any type. – khanh Feb 27 '19 at 17:18
  • @NgọcKhánhNguyễn then have a look at the From traits. They're the normal way to produce those transformations. But it wouldn't make sense for any arbitrary type, unless you have some specific semantic, in which case you really should use some type aliasing. – Denys Séguret Feb 27 '19 at 17:24

1 Answers1

8

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;
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Peter Hall
  • 53,120
  • 14
  • 139
  • 204