【发布时间】: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 | | }
| |_^
【问题讨论】:
-
这看起来像XY question。真正的目标是什么?你不是在寻找类型别名吗?
-
@DenysSéguret 我真正的目标是 usize::new(
) 从任何类型返回一个使用数字。 -
@NgọcKhánhNguyễn 然后看看 From
特征。它们是产生这些转换的正常方式。但这对于任何任意类型都没有意义,除非你有一些特定的语义,在这种情况下你真的应该使用一些类型别名。
标签: rust type-conversion traits primitive-types rust-crates