rust - 为什么对 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>
更改值,但变量仍然是。Same
None
None
解决方案
在编程时,学习如何创建最小、完整和可验证的示例是一项非常重要的技能。这是一个解决您的问题的方法:
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));
}
相反,您想创建一个单例。
也可以看看:
推荐阅读
- javascript - 测量同一类元素的总高度
- amazon-web-services - Lightsail 是迁移 Mac OS 服务器内容的正确解决方案吗?
- jquery - windows Chrome 放大显示半屏
- javascript - 如何在跨度内包装字母,包括标点符号和特殊字符?
- iis - 在 windows server 2016 上发布 PHP web
- python - 以编程方式将 GeoJSON 渲染到图像文件
- wordpress - Wordpress:漂亮的永久链接在 ubuntu 服务器中不起作用
- java - 如何验证输入的值是一种颜色
- vba - 将一组变量声明为另一个变量的函数
- javascript - JavaScript 多输入验证