When i get a field from static struct, borrowed value does not live long enough

This code will report an error :sys does not live long enough E0597 borrowed value does not live long enough in sys.find_mut_env(env_id);

	let application = match SIMULATION_APPLICATION.write() {
		Ok(mut sys) => {
			println!("Enable env {}", env_id);
			let option = sys.find_mut_env(env_id);
			option
		}
		Err(_) => None
	};

and this is SimulationApplication:

#[derive(Debug, Clone)]
pub struct SimulationApplication {
	pub envs: HashMap<i32, Environment>,
}

impl SimulationApplication {
	pub fn new() -> SimulationApplication {
		SimulationApplication {
			envs: HashMap::new(),
		}
	}

	pub fn find_envs(&self) -> Vec<&Environment> {
		self.envs.values().collect::<Vec<_>>()
	}

	pub fn find_env(&self, id: i32) -> Option<&Environment> {
		self.envs.get(&id)
	}

	pub fn find_mut_env(&mut self, id: i32) -> Option<&mut Environment> {
		println!("find_mut_env: {}", id);
		self.envs.get_mut(&id)
	}
}

lazy_static! {
   pub  static ref SIMULATION_APPLICATION: RwLock<SimulationApplication> = {
     let simualtion = RwLock::new(SimulationApplication::new());
        simualtion.write().unwrap().envs.insert(1, Environment {
        id: 1,
        name: "dev",
        state: 0,
        address: "localhost",
        db_prop: DbProp {
            host: "localhost",
            port: 3306,
            user: "root",
            password: "root",
        },
        mq_prop: MqttProp {
            host: "localhost",
            port: 1883,
            user: "root",
            password: "root",
        },
         robot_db_pool: None,
         robots: HashMap::new(),
        }
    );
        simualtion
    };
}

how can i fix it

You can't return reference to the value inside RwLock. You have to store the lock guard and only then use find_mut_env.

4 Likes
let guard = match SIMULATION_APPLICATION.write();
let application = guard {
	Ok(mut sys) => {
		println!("Enable env {}", env_id);
		let option = sys.find_mut_env(env_id);
		option
	}
	Err(_) => None
};

Should guarantee the write guard lives long enough to let you return option from the match expression.

2 Likes

thanks to your answer! i solve it

:smile: this is right! Thanks

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.