如何将 Rust 泛型类型限制为空类型?我需要创建一个具有可选值的类型,这样如果泛型类型是()
,它就不会使用任何内存。这是一个简单的例子 -Data
可以是 a i32, ()
(4 字节),也可以是i32, i32
(8 字节)。add()
两种情况都有一个。我收到此错误(这是有道理的,但不确定如何避免它)。我需要处理所有有效的数字类型。
error[E0119]: conflicting implementations of trait `std::ops::Add` for type `Data<(), ()>`
...
note: upstream crates may add a new impl of trait `num_traits::Num` for type `()` in future versions
Run Code Online (Sandbox Code Playgroud)
error[E0119]: conflicting implementations of trait `std::ops::Add` for type `Data<(), ()>`
...
note: upstream crates may add a new impl of trait `num_traits::Num` for type `()` in future versions
Run Code Online (Sandbox Code Playgroud)
问题在于您无法控制()
类型,因此有人可以在您完全不知情且没有恶意的情况下编写impl
破坏您的代码的类型。Rust 禁止这种远距离的行为。
幸运的是,()
是一种非常简单的类型。所以我们可以自己制作。
#[derive(Clone, Copy)]
struct MyUnit;
Run Code Online (Sandbox Code Playgroud)
MyUnit
基本上是相同的,()
只是它在你的板条箱中,而不是 Rust 的 stdlib 也不是别人的板条箱中。如果有人写了一个impl
for MyUnit
,那么他们一定已经将你的板条箱作为依赖项,因此意识到了风险。然后用of 而不是来写你的impl
s 。它仍然是零大小类型,因此受到与.Data<T, MyUnit>
Data<T, ()>
()
归档时间: |
|
查看次数: |
1214 次 |
最近记录: |