Rust is driving me crazy. Since a couple of hours I try to return the string value of an option field in a struct.
This is the code:
lazy_static! {
pub static ref DATA: Data::new();
}
pub struct Data {
pub filec: Option<String>,
}
impl Data {
pub fn new() -> Self {
Data {
filec: Option::None,
}
}
pub fn get_filec_content<'a>(&'a mut self) -> &'a str {
if self.filec.is_none() {
self.filec = Some(read_file("file.txt"));
}
&self.filec.unwrap()
}
}
pub fn get_filec() {
// How can I return the content of the file in here?
}
fn read_file(filename: &str) -> String {
let content = fs::read_to_string(filename)
.expect(&format!("Failed reading file: {}", filename));
content
}
In another module, I basically just want to call get_filec() and this should return either a &str with the file content. The functions get_filec_content() is just public, because they need to be public to be called via the lazy_static! macro, or am I wrong?
I clearly loose my mind. It can't be too hard to simply return a string value in rust. But it's driving me crazy, I have tried so many things, and nothing is working.
Thank you for helping me with this (probably super simple) problem.
Regards
max
Unwrapping an Option consumes the Option (you can tell by looking at the signature of the method - it takes self, not &self or &mut self). Therefore, if you do self.filec.unwrap(), you've effectively removed the value of self.filec and left it unassigned, which is not allowed.
What you should do instead, is use the .as_ref() method before calling .unwrap() - this takes an Option<T>, and turns it into a new Option<&T>. Then when you unwrap it, you're only consuming the reference, not the original value.
However, that only gives you Option<&String> - you still then need to transform that into Option<&str>. In a lot of places Rust will do this coercion for you, but this isn't one of them, unfortunately.
You can't unwrap the option because that means the String is moved out. There is Option::as_ref which will take a reference to the value in the option. You can unwrap that: