I want to know the difference between a slice ([T]) and a reference to a slice (&[T]). I do not get how slices are unsized types, can't the compiler deduce the size of a slice through the source code?
I understand we need a reference to a slice to make it useful however, this would only make sense If I understand how slices are unsized.
Moreover, I wanted to know the difference between str and &str. I know one is a slice and the other is a reference to a slice and that &str stores a reference to the start of the string and the length as well. But it confuses me as to why we can't use str alone without the reference. Why can't we store the size within the str slice itself. Why do we need a reference to it. I come from a c++ background so maybe using c++ types and terminologies can clear things up!
The reference, &[T] or &str is just a pointer (and a length). Where does this pointer point at? It points at some data. This data is the [T] (or str), the slice itself, the actual bytes of the data. There is no correspondance to that in C++.
Since the data can be of any length, there is no much we can do with [T]. We cannot take it as a parameter, we cannot return it, it always has to be wrapped with some kind of reference. Usually it's & or &mut, but it can also be Box or Rc or Arc, for owned slices.
Sometimes, the compiler could infer the slice size (e.g. when we're slicing via a closed constant range). But a slice type never encodes the length. Only a reference to it does, at runtime. This is because it is useful to have some data that can be of any runtime-determined length, like C++'s std::span or std::string_view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With