简体   繁体   中英

What does `Vec<T>` mean?

The Rust Book sometimes says things like "here we want a Vec<T> ".

Does this mean anything other than "a thing of type Vector?" Also, how would you pronounce it - "vec tee"?

Vec<T> means "A vector of items. The items are of type T ". Let's unpack that a bit...

A vector is a data structure that contains zero-or-more items of the same type. The items have an order, and you can access the items by index (0, 1, ...). You can add and remove items. The items themselves are stored in a contiguous heap-allocated area.

T is a common generic type parameter . A type parameter allows you to write code that abstracts over a specific type, without caring what that type is. In this example, we can create a MyThing with any kind of inner value:

struct MyThing<T> {
    thing: T,
}

Here, T is a type parameter, as it is enclosed in the <> . It doesn't have to be a T , it could be S or Z or MyLittlePony . However, it's common to use T as a shorthand for "type". It's also common to use single-letter names to avoid clashing with concrete type names.

As humans, we will sometimes be a little fast-and-loose with terminology and use T in the same way we might use x in mathematics or foo in programming - a thing we don't care to specify yet.

I would pronounce it aloud as "vec tee" or "a vec of tee", but this is pretty subjective.

Vec<T> is a generic type indicating a vector where each element has type T . See the sections on vectors and generics for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM