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.
- 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).
static
andmut
almost never go together.- As the error says,
static
requires things to be constant. This can be worked around using thelazy_static
crate. - 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
.
You should very probably just take an argument.
The current "recommended" way would be to use once_cell
not lazy_static
:
// on nightly :
#![feature(once_cell)]
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?
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.
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.