如何向现有原始类型添​​加构造函数?

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

我正在尝试通过将 new 方法添加到 usize:

来创建基本类型和对象类型
impl usize {
    fn new(value: &u32) -> usize {
        value as usize
    }
}

我不知道这条消息试图表达什么:

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 | | }
  | |_^

您不能直接在您自己的 crate 之外的类型上实现方法。但是,正如帮助消息所说,您可以定义一个新特征,然后实现它:

pub trait NewFrom<T> {
    fn new(value: T) -> Self;
}

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

不过,这还是有点奇怪。通常你只会使用内置的转换:

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