如何将构造函数添加到现有基元类型?

问题描述 投票:0回答:1

我试图通过将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 | | }
  | |_^
rust type-conversion traits primitive-types rust-crates
1个回答
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;
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.