Variable Lifetimes

I am working on creating a program for a project and am having trouble getting past a curtain error, I am rather new to programing rust.

static mut PLANET: &str = "";

pub fn recive_planet(variable: String) -> String{
    let var = variable;
    else {
        let temp: &str = &var;
        unsafe { PLANET = temp};
        return unsafe { PLANET.clone().to_string() };


At the end of the code segment I am attempting to same the variable temp to a static value outside of the function and when I do that I get an error saying

error[E0597]: `var` does not live long enough
  --> src\components\molecules\
22 |         let temp: &str = &var;
   |                          ^^^^
   |                          |
   |                          borrowed value does not live long enough
   |                          assignment requires that `var` is borrowed for `'static`
27 | }
   | - `var` dropped here while still borrowed

I have been trying to look around to find answers to no luck, I understand that it's because of the scope and that that due to the variable temp being located inside of the function restricts it from being pulled out. I just have no idea how to go about fixing this issue.

You could use this:

use std::boxed::Box;

let temp: &str = Box::leak(var.into_boxed_str());

Although I'm not sure if the use of a global mutable static variable is necessary here?

1 Like

First, don't use static mut or anything else that requires unsafe until you have a lot more Rust experience.

And probably even then, don't use static mut, it's so hard to get right the experts routinely fail to do so.

Consider designing your program so data is owned and passed around, not global.

If you really need a global, use the once_cell crate for now. (The functionality will be in std some day.)


As for an explanation... I'm not sure what parts you don't understand.

String contains owned, growable string data while &str is a reference into some string data stored elsewhere.

A &'static str (which a static &str must be) is a reference to some string data either stored in the executable itself, or which has been leaked to the heap and can't be deallocated.

Rust variables go out of scope at the end of their declared block and get deallocated, and Rust variables also require exclusive access (no outstanding references) when moved.

So a &str borrowing a local variable cannot be a &'static str since the variable is going to go out of scope (or be returned -- moved) by the end of the function. The &str would immediately dangle.

The two solutions offered which don't get rid of your static PLANET are to leak the data or to use owned data (String) instead of a &str.


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.