【发布时间】:2018-07-14 11:24:26
【问题描述】:
我有一个关于 Rust 泛型的小问题。我想让 Array 的长度成为类型参数。
问题:Rust 目前是否支持该功能? 错误消息并不表示缺少功能,而是编程错误。
我想做的例子:
fn create_array<C: ConstSize>(){
let arr = [64; C::SIZE];
println!("array.len: {:?}", arr.len());
}
pub trait ConstSize {
const SIZE: usize;
}
一些示例实现:
fn main() {
create_array::<Five>();
}
struct Five {}
impl ConstSize for Five {
const SIZE: usize = 5;
}
但是编译器告诉我:
no associated item named 'SIZE' found for type 'C' in the current scope
但是,以下工作:
fn create_array(){
let arr = [64; Five::SIZE];
println!("array.len: {:?}", arr.len());
}
See the example on the Rust Playground
感谢您的关注。
【问题讨论】:
-
它看起来像一个编译器错误。有相关问题github.com/rust-lang/rust/issues/52070
-
这回答了我的问题。你可以把它写成一个单独的答案。
-
区别非常微妙:链接的问题一般询问如何解决该问题,答案是 Rust 的未来功能,但这个问题中的具体解决方案现在应该实际上可以工作(但是这是一个错误)