问题
Using the lazy_static
library to create a singleton. I am unable to access that singleton in a module in another file. If the module is defined below the main function I can access it fine.
Given a main file such as the following, test_stuff
can access gamedata fine:
extern crate gamedata;
#[macro_use]
extern crate lazy_static;
lazy_static! {
pub static ref GAMEDATA: &'static str = "I am a test STrings";
}
fn main() {
println!("Game Data:{}",*GAMEDATA);
let obj = gamedata::readinginstatic::readinginstatic {
structure:"working".to_string()
};
obj.print_static();
}
mod test_stuff {
use ::GAMEDATA;
fn printthing() {
println!("herenow:{}", *GAMEDATA);
}
}
With a lib.rs
file such as:
pub mod readinginstatic;
And a module in another file readinginstatic.rs
as described below:
use ::GAMEDATA;
pub struct readinginstatic {
pub structure:String,
}
impl readinginstatic {
pub fn print_static(&self) {
println!("In Print static width:{}", *::GAMEDATA);
}
}
I get the error:
not found in the crate root
When trying to import GAMEDATA
.
Is it possible to access a lazy_static
singleton in another module if it is defined in another file?
To insure I have provided a Minimal, Complete, and Verifiable example here is my whole example code on GitHub: https://github.com/camccar/moduleError
回答1:
::GAMEDATA
refers to some value called GAMEDATA
in the crate root of the gamedata
crate. However where you defined GAMEDATA
was not in that crate, it was in your main.rs
file which has gamedata
as a dependency.
So what you're trying to do here is reach out of a crate use something from the crate that is depending on you, which I'm not sure but I don't think is allowed.
You could consider inverting this and instead initialising GAMEDATA inside your gamedata
crate instead and if you need to use it in main you can just use
it normally:
extern crate gamedata;
use gamedata::GAMEDATA;
fn main(){
println!("Game Data:{}", *GAMEDATA);
...
}
Alternatively if GAMEDATA
is not something your game data crate should know how to define, you could construct it inside main and pass it to some function in the gamedata
crate as a parameter.
来源:https://stackoverflow.com/questions/52133796/rust-cant-import-singleton-from-global-space-into-another-module-in-another-fil