rust - What is the idiomatic lifetime for the "next" pointer in a linked list? -


i'm trying make simple simple linked list type class have pointer next node, running issues. proper way this?

what have this:

trait base {     fn connect<'a, 'b>(&'a self, next: &'b base); }  struct mystruct<'b> {     next: option<&'b base>, // should swapped out reference base next node }  impl<a', b'> base mystruct<'b> {     pub fn new() -> mystruct<'b'> {         mystruct { next: none, }     }      pub fn connect<'a, 'b>(&'a self, layer: &'b base) {         self.next = some(layer);     } } 

the way picture lifetime struct/node connected should should same initial node (i.e. when deallocate list should entirely) should have 1 lifetime. however, believe causes issues when there self pointer in connect function.

you

i have pointer next node

your code shows reference, not pointer, take mean reference. say

when deallocate list should entirely

these 2 concepts incompatible. thing can drop item thing owns item. done giving ownership , nothing else taking ownership. reference, do not own anything, borrowing it.

now, have owned pointer next item. that's box, represents heap-allocated item. no lifetimes need come play, , covered in this answer.

this type of list generic, store owned item string, or reference &u32. when list or list node dropped, string dropped too. references technically dropped, dropping reference not drop referred-to item.

creating linked list references next node is... tricky least, , not useful.

your node this:

struct node<'a> {     next: option<&'a mut node<'a>>, } 

you'd have declare , allocate each , every node yourself, since there'd store node on stack inside hypothetical "add" method.

you going run issue overlapping lifetimes reference next node , lifetime next node has (apply induction list , gets complicated.)

tl;dr it's not clear why want this, it's not easy (or worth it, in opinion).


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -