Reputation: 755
I define a const variable in main.rs and want to use it in different file.
in src/main.rs
, I define such const, no matter and pub or not, it didn’t use:
const CONFIG_GROUP: &str = "core.hydra.io";
pub const CONFIG_VERSION: &str = "v1alpha1";
pub const COMPONENT_CRD: &str = "componentschematics";
fn main() {
...
}
and in another file src/abc.rs
, I want use this const.
It doesn't work, whether use ::
or not.
println!("{}", COMPONENT_CRD);
let component_resource = RawApi::customResource(COMPONENT_CRD)
.within(top_ns.as_str())
.group(::CONFIG_GROUP)
.version(::CONFIG_VERSION);
It reports :
|
208 | println!("{}", COMPONENT_CRD);
| ^^^^^^^^^^^^^ not found in this scope
error[E0425]: cannot find value `CONFIG_CRD` in this scope
--> src/abc.rs:209:54
|
209 | let config_resource = RawApi::customResource(CONFIG_CRD)
| ^^^^^^^^^^ not found in this scope
error[E0425]: cannot find value `CONFIG_VERSION` in the crate root
--> src/abc.rs:210:24
|
210 | .version(::CONFIG_VERSION)
| ^^^^^^^^^^^^^^ not found in the crate root
error[E0425]: cannot find value `CONFIG_GROUP` in the crate root
--> src/abc.rs:211:22
|
211 | .group(::CONFIG_GROUP)
| ^^^^^^^^^^^^ not found in the crate root
Upvotes: 3
Views: 2716
Reputation: 21259
I assume that we're talking about Rust 2018 edition. I'd recommend to read the Path clarity section, especially this part:
The prefix
::
previously referred to either the crate root or an external crate; it now unambiguously refers to an external crate. For instance,::foo::bar
always refers to the namebar
inside the external cratefoo
.
Use can't use ::CONFIG_VERSION
, ::main::CONFIG_VERSION
, etc. Couple of options:
crate::CONFIG_VERSION
directlyuse crate::CONFIG_VERSION
and use just CONFIG_VERSION
abc.rs
content:
pub(crate) fn foo() {
println!("{}", crate::CONFIG_VERSION);
}
Another abc.rs
variant:
use crate::CONFIG_VERSION;
pub(crate) fn foo() {
println!("{}", CONFIG_VERSION);
}
main.rs
content:
pub(crate) const CONFIG_VERSION: &str = "v1alpha1";
mod abc;
fn main() {
abc::foo()
}
Upvotes: 2