Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion between [T] and &[T]

Tags:

arrays

slice

rust

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 elements T, while
  • &[T] is a sized fat pointer and points to a sequence of elements T.

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!

like image 956
Jämes Avatar asked Sep 05 '19 15:09

Jämes


People also ask

Have confusion meaning?

1 : difficulty in understanding or in being able to tell one thing from a similar thing. 2 : a feeling or state of uncertainty. confusion. noun. con·​fu·​sion | \ kən-ˈfyü-zhən \

How do you teach difference between B and D?

Luckily, both b and d come at the beginning of the alphabet - the part that most young children can remember! b comes before d. Visualise a bed with the stalks of the b and the d making the bedhead and the foot of the bed. b comes before d so b has its stalk to the left, d to the right.


1 Answers

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

like image 139
Peter Hall Avatar answered Oct 10 '22 19:10

Peter Hall