Rust 为什么我的常量变量可以';在不同的模式中找不到
我在main.rs中定义了一个const变量,并希望在不同的文件中使用它 在Rust 为什么我的常量变量可以';在不同的模式中找不到,rust,Rust,我在main.rs中定义了一个const变量,并希望在不同的文件中使用它 在src/main.rs中,我定义了这样的常量,无论是否发布,它都没有使用: const CONFIG_GROUP: &str = "core.hydra.io"; pub const CONFIG_VERSION: &str = "v1alpha1"; pub const COMPONENT_CRD: &str = "componentschematics"; fn main() { ... }
src/main.rs
中,我定义了这样的常量,无论是否发布,它都没有使用:
const CONFIG_GROUP: &str = "core.hydra.io";
pub const CONFIG_VERSION: &str = "v1alpha1";
pub const COMPONENT_CRD: &str = "componentschematics";
fn main() {
...
}
在另一个文件src/abc.rs
中,我想使用这个常量
无论是否使用:
,它都不起作用
println!("{}", COMPONENT_CRD);
let component_resource = RawApi::customResource(COMPONENT_CRD)
.within(top_ns.as_str())
.group(::CONFIG_GROUP)
.version(::CONFIG_VERSION);
报告说:
|
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
我想我们说的是2018版。我建议阅读本节,尤其是这一部分: 前缀
::
以前指的是板条箱根或外部板条箱;现在它明确地指的是一个外部板条箱。例如,::foo::bar
总是指外部板条箱foo
内的名称bar
使用不能使用::CONFIG_VERSION
,::main::CONFIG_VERSION
等。两个选项:
- 直接使用
板条箱::配置\u版本
- 导入它
并只使用使用板条箱::配置_版本
配置_版本
abc.rs
内容:
pub(板条箱)fn foo(){
println!(“{}”,板条箱::配置_版本);
}
另一个abc.rs
变体:
使用板条箱::配置_版本;
酒吧(板条箱)fn foo(){
println!(“{}”,配置版本);
}
main.rs
内容:
发布(板条箱)常量配置版本:&str=“v1alpha1”;
mod abc;
fn main(){
abc::foo()
}
是否添加了
使用
?8 |使用配置| CRD;| ^^^^^不CONFIG\u CRD
外部机箱不能使用use
正如@DenysSéguret所说,您是否在src/abc.rs
中编写使用pkg\u name::CONFIG\u CRD
?我编写使用机箱::CONFIG\u CRD代码>在abc.rs
中,但它在根目录中告诉noCONFIG\u CRD
。当我写pub(crate)const CONFIG_CRD:&str=“operationalconfigurations”就像你说的。我的版本是:``rustc 1.36.0(a53f9df32 2019-07-03)``我发现我必须在mod abc之前编写这个常量代码>为什么?我发现如果我定义发布(板条箱)const CONFIG_VERSION:&str=“v1alpha1”代码>和mod abc代码>在另一个文件中src/lib.rs
。然后我可以在src/abc.rs
中使用const,而现在我不能在main.rs
中使用它。然后放下(板条箱)
,只使用pub
。看见