Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `Vec<T>` mean?

Tags:

rust

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"?

like image 746
Nathan Long Avatar asked Dec 14 '22 14:12

Nathan Long


2 Answers

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.

like image 168
Shepmaster Avatar answered Dec 19 '22 11:12

Shepmaster


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.

like image 27
Jeff Ames Avatar answered Dec 19 '22 11:12

Jeff Ames