是否可以使用泛型的类型参数来控制数组的大小? [英] Is it possible to control the size of an array using the type parameter of a generic?
问题描述
以下内容仅用作示例,并非有效的 Rust 代码.
What follows is just used as an example, and not valid Rust code.
struct Vec<T: Sized, Count> {
a: [T; Count]
}
类似的东西在 C++ 模板中是可能的,但我没有在 Rust 中看到过.
Something like it is possible in C++ templates, but I haven't seen it in Rust.
推荐答案
Rust 1.51
使用常量泛型:
struct Vec<T: Sized, const COUNT: usize> {
a: [T; COUNT],
}
以前的版本
RFC 2000 — const 泛型 引入了对此的支持进度在 issue #44580 中进行跟踪.
Previous versions
RFC 2000 — const generics introduces support for this and progress is tracked in issue #44580.
如果您查看 Rust 的设计,您会注意到它首先解决了最困难的问题(内存安全、无数据竞争),但在其他方面还有很多不完整"的地方.(与可以实现的目标相比).
If you look at the design of Rust, you will notice that it started first by tackling the hardest problems (memory-safe, data-race free) but there are otherwise lots of areas where it is "incomplete" (compared to what could be achieved).
特别是,通用结构和函数开始时有些受限:
In particular, generic structures and functions started out somewhat limited:
- 缺乏更高级的类型 (HKT)
- 缺少非类型参数=>数组是特殊情况,为数组实现 trait 是一个已知问题,解决方法是针对几个不同的维度实施它
- 缺少可变参数=>元组是特殊情况,为所有元组实现一个特征同样困难
- lack of Higher Kinded Types (HKT)
- lack of non-type parameters => arrays are special-cased, and implementing a trait for an array is a known issue, the work-around being to implement it for a few different dimensions
- lack of variadic parameters => tuples are special-cased, and implementing a trait for all tuples is similarly difficult
目前,并非所有这些都已实施,不是因为不需要它们,而仅仅是因为时间不够.Rust 1.0 的想法不是发布不会进化的最终产品,而是发布一个稳定的基础;部分或全部会来.
For the moment, not all of these are implemented, not because they are not desired but simply because time was lacking. The idea of Rust 1.0 was not to release a final product that would not evolve, but a stable base from which to start; some or maybe all will come.
这篇关于是否可以使用泛型的类型参数来控制数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!