rust - Why do slices in a structure require a lifetime, but not vectors? -



rust - Why do slices in a structure require a lifetime, but not vectors? -

when define next structure:

struct test<'a> { a: &'a [i64], b: vec<i64>, }

both piece , vector contain pointer. why piece require lifetime, not vector?

a vector owns elements. means vector responsible allocating , freeing elements points to. lifetime of vector's elements same lifetime of vector itself, there's no need specify lifetime vec type.

a piece borrows elements of vector or array may allocated statically or dynamically. piece must indicate lifetime of borrowed elements compiler can create necessary safety checks.

another way express comparing sequence of events between 2 options.

for vector:

a vec allocated. no storage allocated elements (when vec empty). as elements added vector, storage elements allocated heap. vec stores pointer storage. when vector dropped, storage elements first freed, vec freed.

for slice:

some storage allocated array or vector of elements, either statically or dynamically. a piece allocated , initialized reference or of elements of storage. piece stores pointer first element. when piece dropped, storage elements not freed, because piece doesn't own it; piece dropped. if storage allocated dynamically, freed.

edit

generally speaking, lifetime annotation required on borrowed pointers (&'a x), on types contain borrowed pointers (x<'a>, x struct or enum has fellow member borrowed pointer) , on trait objects/constraints (x+'a, x trait) when types used members of struct or enum.

on let bindings , on right-hand side of as operator, write borrowed pointer types without lifetime annotation (i.e. &x), because compiler infers lifetime in case.

what need remember lifetime annotations necessary when dealing borrowed pointers, either straight or indirectly.

if want larn more ownership, borrowing , lifetimes, suggest read the rust guide's section on pointers rust references , lifetimes guide

rust

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -