How to create a static file

Hi everybody
I am having trouble defining a static variable in the path or name of a file.
I want some function to be able to write to the file without me passing it to the function as a parameter, rather it will recognize it because it is a global variable.
Thank you so much!

Lots of red flags here.

  1. Global variables are usually a bad idea, except a few specific cases (like when you have a truly global state, and the function signatures are constrained by a trait, so you can't pass it in).
  2. static and mut almost never go together.
  3. As the error says, static requires things to be constant. This can be worked around using the lazy_static crate.
  4. The type must be Path not &Path.

This should almost never be a reason to have globals.
Also, I don't think you need a mut. Just initialize it as follows:

lazy_static! {
       static ref PATH_TO_FILE = Path::new("<path>");

If you absolutely need mut, you'd need a Mutex to wrap around the Path.

1 Like

You should very probably just take an argument.

The current "recommended" way would be to use once_cell not lazy_static :

// on nightly :
use std::lazy::SyncLazy;
// or on stable :
// use once_cell::sync::Lazy;

use std::path::PathBuf;

static PATH: SyncLazy<PathBuf> = SyncLazy::new(|| PathBuf::new());

Thanks so much for the explanations
I tried to put what you suggested and I get the following error:


Basically, I want to write to a file that I receive as input from a function without sending the file name/path

The lazy_static! macro is from an external crate that you have to import in your Cargo.toml.

Why don't you want to send?

1 Like

I still get this message

Did you read what @alice answered? You have to declare external dependencies in Cargo.toml. But since this is so basic, it is explicitly covered in the Book, which you surely consulted before asking a question?

Thank you very much, I'm new to this language, now I understand what Alice meant. I will read about it.

Do you have any idea why am I still getting the error?

You have to specify the type.

1 Like

Have you considered just using a string?

static PATH_TO_FILE: &str = "<path>";

Then when you use it you can do Path::new(PATH_TO_FILE) if necessary. This doesn't need the lazy_static! crate.


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.