问题
I'm currently confused by [T]
and &[T]
in Rust. Let's start by what I know:
[T; n]
is an array of n elements,&[T; n]
is a pointer to an array with n elements,[T]
is unsized and points to sequence of elementsT
, while&[T]
is a sized fat pointer and points to a sequence of elementsT
.
My confusion starts with the naming convention of the two items. From the documentation of Rust, they provide the following example:
let a: [i32; 5] = [1, 2, 3, 4, 5]; // An array of type [T, n]
let slice: &[i32] = &a[1..3]; // A slice of type &[T]
and states
This slice has the type &[i32].
So, I assume &[T]
is called a slice. What's the name of the item [T]
so ? What is the usage of [T]
exactly ? You can't embed it into a struct (it's unsized), you can't take this type in parameter for the same reason. I can't figure out a practical usage of it.
Thanks!
回答1:
What's the name of the item
[T]
so ? What is the usage of[T]
exactly ?
[T]
is a block of contiguous memory, filled with items of type T
. It is rarely referred to by name directly because it needs to be behind a pointer to be useful. That is usually a &[T]
, commonly referred to as a slice, but could also be other pointer types.
The term "slice" is overloaded, but it is not usually a cause of confusion since it really doesn't come up much. In general, if the word "slice" is used by itself then it means &[T]
. If it has some other modifier, then it probably refers to a different pointer type. For example Box<[T]>
is a "boxed slice" and Rc<[T]>
might be called a "ref-counted slice".
回答2:
Regarding slices:
E.g. string literals are slices of type &str. But slices of Strings (of type String) are also of type &str such as slice: &str = &String [0..n-1]
.
Furthermore, slice: &[T] in:
Arrays like
array: [T; n]
- if you want a piece of it, you can take aslice = &array [1..n-1]
which means that slice is of type &[T].Vectors such as
vector: Vec<T>
you can take a part of it as a slice: &[T].
来源:https://stackoverflow.com/questions/57808948/confusion-between-t-and-t