I am trying to create a struct to manipulate file storage, but after I change the value it can not be used. I'm sure it's about lifetimes, but I do not understand how I can fix this.
use std::error::Error;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader};
use std::option::Option;
use std::path::Path;
pub struct Storage<'a> {
path_str: &'a str,
file: Option<File>,
}
const LOCKED_STORAGE: Storage<'static> = Storage {
path_str: &"/tmp/bmoneytmp.bms",
file: None,
};
pub fn get_instance() -> Storage<'static> {
if LOCKED_STORAGE.file.is_none() {
LOCKED_STORAGE.init();
}
LOCKED_STORAGE
}
impl Storage<'static> {
// Create a file for store all data, if does not alred exists
fn init(&mut self) {
let path = Path::new(self.path_str);
self.file = match OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path)
{
Err(e) => panic!("Couldn't create the storage file at {}", e.description()),
Ok(file) => Some(file),
};
if self.file.is_none() {
panic!("Error on init??"); // This line is not called. Ok :)
}
}
// Check if section exists
pub fn check_section(&self, name: String) -> bool {
if self.file.is_none() {
panic!("Error on check??"); // This line is called. :(
}
true
}
}
fn main() {
let storage = get_instance();
storage.check_section("accounts".to_string());
}
playground
This fails:
thread 'main' panicked at 'Error on check??', src/main.rs:48:13
I am trying to use a method to open a file and read this opened file, but in second method the instance of the file is not opened. Using Option<File>
, I change the value with Same
/None
but the variable continues to be None
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…