Construct an instance that borrows mutable reference of self [solved]



I would like to have a method that constructs an instance of another type and that instance gets mutable reference on the instance which constructs it. Look at this code, please.

There is an error borrowed value does not live long enough about mutable reference on self. It seems I understand what it means. It means I can’t borrow reference by instance that is gonna be owned outside, right? If I am right how to tell the compiler that the constructed instance will live no longer than borrowed instance?

I checked the book and I read a couple of topics on the forum but I really can’t figure out how to fix it. It become looking like impossible without smart pointers and interior mutability.



You just need Wrapper::new(self), as it’s already a reference.

In method declarations, fn foo(&mut self) is syntactic sugar for fn foo(self: &mut Self). You can even write it that way if you prefer, but people will think you’re strange. :wink:



OMG. Sure! I’m stupid code writer, not a programmer. Solved!

1 Like


Some people will, on the contrary, applaud you for being explicit :grin: