Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - Why do changes to a const variable not persist between usages?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When programming, it's a very important skill to learn how to create a Minimal, Complete, and Verifiable example. Here is one for your problem:

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

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

This prints Some(42) — the value of EXAMPLE is not changed.

A const variable has no guarantees about how many instances it will have. The compiler is allowed to have zero, one, or multiple instances of it. Every time you make use of a const, it's as if you created a brand new value right there, pasting in the definition of the constant:

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

Instead, you want to create a singleton.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...