Error:: returns a value referencing data owned by the current function

Before I start: it's shameful for me to ask such basic questions and some of them. But as of now I am helpless, given the timelines etc. Please bear with me.

issue:

impl<'a> MessageRelaySt<'a> {
    pub async fn new() -> MessageRelaySt<'a> {
        let temp = AwsUtilsSt::new().await;
        return Self {
            aws_utils: &Arc::new(temp),
        };
    }
}
error[E0515]: cannot return value referencing temporary value
  --> src/services/messagerelay.rs:14:16
   |
14 |           return Self {
   |  ________________^
15 | |             aws_utils: &Arc::new(temp),
   | |                         -------------- temporary value created here
16 | |         };
   | |_________^ returns a value referencing data owned by the current function

i understand the meaning of the error. But from this info, I can't determine my next course of action. I tried adding a lifetime variable --which of course didn't work.

Why are you trying to put a reference to the Arc in your struct instead of just storing the Arc?

Generally speaking storing a reference to an Arc is an anti-pattern since Arc is a type for sharing a value with runtime reference counting instead of static borrow checking.

2 Likes

I finally solved, after several trials and errors

   pub async fn new() -> Self {
        let temp = AwsUtilsSt::new().await;
        return MessageRelaySt {
            aws_utils: Arc::new(temp),
        };
    }

But I am not sure how this fixed the issue? or will i get the issue in runtime. Even in this, the temp variable is lost once line 2 is crossed. So the compiler should have complained --which didn't happen.

also, during the trial and error, i noticed an error that said that we cant return self in async. Not sure why that error doesn't come now,

The variable is gone, but the value you put in temp was moved out of it by Arc::new(temp), and the created Arc was moved into the returned MessageRelaySt, so it's all still alive, owned by the MessageRelaySt.

Ownership keeps things alive. References don't.

3 Likes

Yes, that's good. You almost never want to put temporary scope-bound references in structs. They prevent structs from holding the data and make the structs unusable outside of the scope where variables or temporary expressions live that the data has been borrowed from.

Remember that Rust doesn't have a garbage collector, so it can't make anything live as long as it needs. It will make usage of structs with references restricted instead. Don't put references in structs.

1 Like

Does the above implementation change? if yes then can you give the right implementation? Any reference of any document ? --which when followed makes sure i don't fall into all these pits?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.