【问题标题】:How do I add a constructor to an existing primitive type?如何将构造函数添加到现有的原始类型?
【发布时间】:2019-07-21 11:23:18
【问题描述】:

我正在尝试通过将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】:

你不能直接在你自己的 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;

【讨论】:

    猜你喜欢
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    相关资源
    最近更新 更多