Is there beacuse slice length is fixed ?slice is a fixed array , it has fixed number of data , so rust save it to the slack , and no need to manage it using ownership?
or slice just a point Essentially ?
Is there beacuse slice length is fixed ?slice is a fixed array , it has fixed number of data , so rust save it to the slack , and no need to manage it using ownership?
or slice just a point Essentially ?
By definition. The point of the borrowed slice is not to have ownership. For owned equivalent there's Box<[T]>
, arrays and Vec
.
There needs to be a type that allows borrowing of multiple elements of a collection.
Slices can be stored on the heap (eg. Vec<&[T]>
) and can be made smaller s = &s[1..];
, so it's not about any technical limitation. It's the goal in itself.
BTW: If you're coming from Go, then Go's slices are a different data type from Rust's slices. Go slices have shared ownership, so they're vaguely like Rc<Vec<T>>
(but still not quite, as the exact equivalent needs GC).
[T]
can own data. That's precisely what it's doing in Box<[T]>
.
&[T]
does not own data, because it is a borrow.
A slice in rust is more abstract than "an object you can own", instead it's more like "some data in memory that can be interpreted like a set of T
s". Therefore, it is not something that you can simply "own" without a pointer, because it is simply continuous data, and is made to be worked with behind a pointer of some sort. That pointer can be an owning pointer (Box<[T]>
) or a non-owning pointer (&[T]
or &mut [T]
). When you say [T]
in rust, you really mean, some continuous data, which has no real defined size, because the size is not encoded in the [T]
type, instead it is encoded in the &[T]
type which is special.
Lets say I could own a [T]
:
let x: [usize] = [1, 2, 3];
Then what could I do with it? Really, nothing right now*, because:
size_of::<usize>()
bytes can even be safely interpreted as a usize right now*Also, don't mix up arrays ([T; n]
) and slices ([T]
). Arrays have a constant size defined at compile time, and are therefore constant throughout the program, and can be properly allocated size on the stack (And owned without a pointer).
*There is an rfc mentioned in the next post in this thread which aims to change all of this, so this really only applies right now, and may become invalid in some time (Years, or months) depending on the rust team's focuses
thanks guys. I new to rust , just from golang , what u were said is meaning , I need to comprehend a while.
Welcome to Rust! It's different, but much less malware-prone than other languages. Don't hesitate to post in this forum; you'll almost always get a number of timely, friendly responses.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.