Rust “类型绑定中的特征”;“未实施”吗;?
考虑下面的代码,它使用一个trait将数组的长度固定在类型中Rust “类型绑定中的特征”;“未实施”吗;?,rust,traits,Rust,Traits,考虑下面的代码,它使用一个trait将数组的长度固定在类型中 use std::marker::PhantomData; pub trait MyLen { const LEN: usize; } pub struct Data<L: MyLen> { bytes: [u8; <L as MyLen>::LEN], _phantom: PhantomData<L>, } 使用std::marker::PhantomData; 麦伦
use std::marker::PhantomData;
pub trait MyLen {
const LEN: usize;
}
pub struct Data<L: MyLen> {
bytes: [u8; <L as MyLen>::LEN],
_phantom: PhantomData<L>,
}
使用std::marker::PhantomData;
麦伦酒吧{
常数:使用;
}
发布结构数据{
字节:[u8;::LEN],
_幻影:幻影数据,
}
我可以发誓几天前我看到了类似的代码,但现在我看到了
Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `L: MyLen` is not satisfied
--> src/lib.rs:8:17
|
4 | const LEN: usize;
| ----------------- required by `MyLen::LEN`
...
8 | bytes: [u8; <L as MyLen>::LEN],
| ^^^^^^^^^^^^^^^^^ the trait `MyLen` is not implemented for `L`
|
help: consider further restricting this bound
|
7 | pub struct Data<L: MyLen + MyLen> {
| ^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground`
编译操场v0.0.1(/playerd)
错误[E0277]:未满足特征绑定'L:MyLen'
-->src/lib.rs:8:17
|
4 | const LEN:使用;
|--------------由'MyLen::LEN'要求`
...
8字节:[u8;::LEN],
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^`
|
帮助:考虑进一步限制这个界限
|
7 |发布结构数据{
| ^^^^^^^
错误:由于上一个错误而中止
有关此错误的详细信息,请尝试“rustc--explain E0277”。
错误:无法编译`
这个错误信息对我来说毫无意义,尤其是建议。你知道我做错了什么吗
操场:首先,您需要使用才能做到这一点。但是,这还不够,因为您还需要使用 当您添加
const_generics
功能时,问题会随着更具描述性的编译器错误而变得明显
error: constant expression depends on a generic parameter
--> src\main.rs:37:12
|
37 | bytes: [u8; <L as MyLen>::LEN],
| ^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this may fail depending on what value the parameter takes
error: constant expression depends on a generic parameter
--> src\main.rs:34:30
|
34 | [u8; <L as MyLen>::LEN]: Sized,
| ^^^^^
|
= note: this may fail depending on what value the parameter takes
当然,这需要每晚编译。难道
[u8;size_of::()]
不是比这个“size marker”特性解决方案更清晰的实现吗?@IvanC除非我错过了一些上下文,否则我看不出问题在哪里提到LEN==size_of::()
:)我可能误解了代码,但其目的似乎是让数据拥有“原始”u8用于存储L的缓冲区,并且由于在不同大小的L上使用关联常量是通用的,因此将您限制为每L一个缓冲区大小,大小\u似乎是实现该目标的更直接的途径。@Heinzi,如果您真的想这样做,就像您的问题一样。那么不,这在stable上是不可能的。如果您愿意更改设计,则有可能可能的解决方案,取决于整体上下文:)HeimZi-MixCista泛型特性是由于下一个版本的稳定,所以您可以考虑泛型。