Using String.to_string() with lazy_static

Below is a a code snippet where I am trying to set a static globally available String value using lazy_static. The code below runs, but it seems clunky to me, that whenever I want to get the value I have to call:
(*CONFIG_PATH).to_string()
in order to avoid the error:

error[E0507]: cannot move out of dereference of `CONFIG_PATH`
   ...
    |                   ^^^^^^^^^^^^ move occurs because value has type `std::string::String`, which does not implement the `Copy` trait

Is there some other way to do this more elegantly? Minimal code example and link to rust playground is below.

use std::{fs, env};
use lazy_static::lazy_static;

pub const DEFAULT_CONFIG_PATH: &str = "/var/lib/peachcloud/config.yml";
lazy_static! {
    static ref CONFIG_PATH: String = {
        if let Ok(val) = env::var("CONFIG_PATH") {
             val
        }
        else {
            DEFAULT_CONFIG_PATH.to_string()
        }
    };
}


fn main() {
  println!("CONFIG_PATH: {}", *CONFIG_PATH);
  fs::write((*CONFIG_PATH).to_string(), "test output");
}

(Playground)

fs::write(CONFIG_PATH.as_str(), "test output"); works as expected.

thank you! I didn't realize I could call functions on CONFIG_PATH directly without dereferencing it first with * . I'm a bit confused actually what the type that is returned by lazy_static! is exactly, but I will keep reading about it.

I found this related question to be helpful What is the keyword `ref` in `static ref`?

It's a special type created by the lazy_static! macro whenever you use it, to handle lazy initialization of that one static variable.

You're not the first person to be confused by this; in fact, I recommend using once_cell::sync::Lazy instead of lazy_static!. It does the same thing, but does not use a macro, and does not hide the actual type of the static, so it is more unsurprising. Also, the same interface is planned for the standard library (std::lazy::Lazy), so once that stabilizes you will not need any third-party crate to do it.

5 Likes

Method call syntax auto-(de)refs as deep as needed.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.