I'm writing a function that deserializes the user config file and returns a Config struct that will later be stored in another struct of type App. The code currently looks like this:
impl<'a> Config<'a> {
fn get_config() -> Config<'a> {
let mut path = dirs::config_dir().unwrap();
path.push("todo-rs");
path.push("config.toml");
let content = match fs::read_to_string(path){
Ok(c) => c,
Err(err) => if matches!(err.kind(), std::io::ErrorKind::NotFound) {
return Config::default();
} else{
eprint!("Cannot read config file");
exit(1);
}
};
match toml::from_str(content.as_str()) {
Ok(config) => config,
Err(_) => {
eprint!("Cannot read config file");
exit(1);
}
}
}
}
But i get the following error:
error[E0515]: cannot return value referencing local variable `content`
--> src/app/config.rs:128:27
|
127 | match toml::from_str(&content.as_str()) {
| ---------------- `content` is borrowed here
128 | Ok(config) => config,
| ^^^^^^ returns a value referencing data owned by the current function
I understand the reason of the error, but I cant figure out how to solve it that doesn't involve moving this code to the function that initialises the App struct
