Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

rust - Is it possible to control the size of an array using the type parameter of a generic?

What follows is just used as an example, and not valid Rust code.

struct Vec<T: Sized, Count> {
    a: [T; Count]
}

Something like it is possible in C++ templates, but I haven't seen it in Rust.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rust 1.51

Use const generics:

struct Vec<T: Sized, const COUNT: usize> {
    a: [T; COUNT],
}

Previous versions

RFC 2000 — const generics introduces support for this and progress is tracked in issue #44580.

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:

  • 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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...