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

#1

Hello!

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.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8643e0b1cd31e4f000738358ca06cd20

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.

0 Likes

#2

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:

0 Likes

#3

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

1 Like

#4

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

0 Likes