首页 > 解决方案 > 为什么对 const 变量的更改不会在两次使用之间持续存在?

问题描述

我正在尝试创建一个结构来操作文件存储,但是在我更改了它的值之后它就不能使用了。我确定这与生命有关,但我不明白如何解决这个问题。

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());
}

操场

这失败了:

thread 'main' panicked at 'Error on check??', src/main.rs:48:13

我正在尝试使用一种方法打开一个文件并读取这个打开的文件,但是在第二种方法中,文件的实例没有打开。使用,我用/Option<File>更改值,但变量仍然是。SameNoneNone

标签: rustlifetime

解决方案


在编程时,学习如何创建最小、完整和可验证的示例是一项非常重要的技能。这是一个解决您的问题的方法:

const EXAMPLE: Option<i32> = Some(42);

fn main() {
    EXAMPLE.take();
    println!("{:?}", EXAMPLE);
}

这将打印Some(42)— 的值EXAMPLE未更改。

一个const变量不能保证它会有多少个实例。允许编译器具有它的零个、一个或多个实例。每次使用 aconst时,就好像您在那里创建了一个全新的值,并粘贴了常量的定义:

fn main() {
    Some(42).take();
    println!("{:?}", Some(42));
}

相反,您想创建一个单例

也可以看看:


推荐阅读