I’m new to Rust. And now I have some problems in understanding slice. Of course, slice is very easy to use and understand. But I don’t know the reason why does rust need us to use slice in this way.
In the tutorial, when explain &str
is the slice reference to str
. str
is the slice. And we can create a slice like this
let string: &str = "a string";
let arr:[i32; 4] = [1,2,3,4];
let arr_slice:&[i32] = &arr[..2];
Here, I think, the size of slice is quite clear. arr_slice
has referenced to two i32
elements. If I understand it in C, it will look like:
typedef struct {
void* ptr;
int length;
} slice;
The length can be known through the slice syntax [...]
. Thus, size of slice can also be inferred by sizeof(type of ptr) * length
which behaves like array. So that in the example above, it’s very easy to know the size of slice
itself at compile time.
Why does Rust make slice a DST?