Intro
This blog is written in eng cus ref and concept related to it could be super confusing when translation happens.
All that matters
[T; n]
is an array of lengthn
, represented asn
adjacentT
instances.&[T; n]
is purely a reference to that array, represented as a thin pointer to the data.[T]
is a slice, an unsized type; it can only be used through some form of indirection.&[T]
, called a slice, is a sized type. It’s a fat pointer, represented as a pointer to the first item and the length of the slice.
Array and Slice
ok, first lets learn how to create a array.
Lets picture a scenario, you are a python boy. You want to learn rust to show off to your miserable friends. you create a array based on the spirit of python. And the compiler complained that you should use let i32slice: [i32; 2] = [0, 10];
instead of let i32slice: [i32] = [0, 10];
.
TL; DR.
This part is for those python boy. If you are familiar with c++, you should spit on my blog and go get some comic to read till I finish this stupid lesson.
// in C++
std::array<int, 2> myArray = {1, 10};
[T]
is a contiguous sequence of T
s, while &[T]
is a dynamically-sized view into this contiguous sequence. The former has no statically known size while the latter does. while the lvalue always has an statically known size. If you dont know what lvalue is, go ask Dr.Google, on this I cant help.
Diff between &[T; n]
and &[T]
https://stackoverflow.com/questions/30794235/what-is-the-difference-between-a-slice-and-an-array
About [T]
[T]
is just a concept, you can never create a dynamically sized variable in rust, all you can do is let &[T; n]
coerce to &[T]
and thus exploit the returned fat pointer.