考虑以下代码,该代码使用特征使数组的长度固定在类型中。
use std::marker::PhantomData;
pub trait MyLen {
const LEN: usize;
}
pub struct Data<L: MyLen> {
bytes: [u8; <L as MyLen>::LEN],
_phantom: PhantomData<L>,
}
我可以发誓,几天前我看到类似的代码可以工作,但是现在我看到了
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`
此错误消息对我来说没有任何意义,尤其是建议没有意义。有什么想法我做错了吗?
游乐场:https : //play.rust-lang.org/? version = stable & mode = debug & edition = 2018 & gist =49c9a11106a46125eaa9612560966bac
首先,您需要使用该const_generics
功能才能做到这一点。但是,这还不够,因为您还需要使用const_evaluatable_checked
功能。
添加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
缺少的部分是where [u8; <L as MyLen>::LEN]:
(或where [u8; <L as MyLen>::LEN]: Sized
)需要const_evaluatable_checked
功能。需要where子句,以确保LEN
不会评估溢出或使该数组无效的事物。
您可以在Rust编译器团队在此HackMD帖子上阅读有关它的更多信息。
#![feature(const_generics)]
#![feature(const_evaluatable_checked)]
#![allow(incomplete_features)]
use std::marker::PhantomData;
pub trait MyLen {
const LEN: usize;
}
pub struct Data<L: MyLen>
where
[u8; <L as MyLen>::LEN]: ,
// or
// [u8; <L as MyLen>::LEN]: Sized,
{
bytes: [u8; <L as MyLen>::LEN],
_phantom: PhantomData<L>,
}
当然,哪个程序需要每晚编译。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句