Vector owns its elements. This means that the vector is responsible for highlighting and releasing the elements it points to. The lifetime of the vector elements coincides with the lifetime of the vector itself, so there is no need to specify the lifetime for the Vec type.
A slice takes up elements of a vector or array that can be distributed statically or dynamically. The slice should indicate the lifetime of the borrowed elements so that the compiler can perform the necessary security checks.
Another way to express this is to compare the sequence of events between two parameters.
For the vector:
- A
Vec . No memory is allocated for items at first (when Vec empty). - When elements are added to the vector, memory for the elements is allocated from the heap.
Vec stores a pointer to this store. - When a vector is discarded, the memory for the elements is first freed, and
Vec itself is freed.
For fragment:
- Some storage is allocated for an array or element vector, statically or dynamically.
- A slice is clipped and initialized to refer to some or all of the elements of this repository. A slice stores a pointer to the first element.
- When a slice is discarded, storage for items is not freed because the slice does not belong to it; only the slice is discarded.
- If storage was dynamically allocated, it will eventually be freed.
EDIT
Generally speaking, borrowed pointers ( &'a X ) require annotation for the lifetime, for types that contain borrowed pointers ( X<'a> , where X is a struct or enum that has a member that is a borrowed pointer) and objects / object constraints ( X+'a , where X is trait ) when these types are used as members of a struct or enum .
In let bindings and on the right side of the as operator, you usually write borrowed pointer types without annotation for life (i.e. just &X ), because in this case the compiler displays the lifetime.
What you need to remember is that annotations of the lifetime are necessary when working with borrowed pointers , directly or indirectly.
If you want to know more about ownership, borrowing, and lifespan, I suggest you read the Rust manual on pointers , as well as the Rust References and Lifetimes Manual
Francis gagné
source share