如何将构造函数添加到现有原始类型?

时间:2019-02-27 16:49:24

标签: rust type-conversion traits primitive-types rust-crates

我试图通过将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 | | }
  | |_^

1 个答案:

答案 0 :(得分:3)

您无法在自己的板条箱之外的类型上直接实现方法。但是,如帮助消息所述,您可以定义一个新特征,然后实施它:

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;