大佬教程收集整理的这篇文章主要介绍了带有通配符使用声明的 Rust 子模块行为,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图了解使用通配符路径时(子)模块导入是如何工作的。我能想到的最简单的演示如下,其中两个模块,或者两个 crate,共享相同的模块结构。@H_801_3@
pub mod priMary {
pub mod a {
pub mod b {
pub struct A(pub i32);
}
}
}
pub mod import {
pub use crate::priMary::*;
// Compiles and executes fine with this commented out,but fails with
// "error[E0433]: Failed to resolve: Could not find `b` in `a`"
// otherwise. The error refers to the usage in the assert_eq macro
// pub mod a {}
}
fn main() {
assert_eq!(import::a::b::A(42).0,42);
}
我的一般想法是,由于第一种情况,其中 pub mod a {}
被注释掉有效,通配符应该将通配符选取的所有子模块扩展为它正在扩展的路径中的子模块。不是这样吗?如果是这样,那么适当的思考方式是什么?@H_801_3@
Use declarations 在这方面没有很多细节。@H_801_3@
use
和 *
导入所有名称,但与当前模块中已存在的名称冲突的名称除外。@H_801_3@
比较:@H_801_3@
pub mod priMary {
pub fn f() {
println!("p::f");
}
}
pub mod import {
pub use crate::priMary::*;
}
fn main() {
import::f();
}
哪个prints p::f
@H_801_3@
pub mod priMary {
pub fn f() {
println!("p::f");
}
}
pub mod import {
pub use crate::priMary::*;
pub fn f() {
println!("import::f");
}
}
fn main() {
import::f();
}
哪个prints import::f
。@H_801_3@
这对于函数和常量来说似乎很明显(否则它会使 *
非常有限,使得上游库无法在不冒破坏下游用户的风险的情况下添加任何项目),但对于模块来说似乎更混乱.
您必须记住,您不能多次定义一个模块(即“重新打开”一个模块)。以下是非法的:@H_801_3@
pub mod priMary {
pub mod a {}
pub mod a {}
}
和fails with@H_801_3@
error[E0428]: the name `a` is defined multiple times
--> src/lib.rs:3:5
|
2 | pub mod a {}
| --------- previous definition of the module `a` here
3 | pub mod a {}
| ^^^^^^^^^ `a` redefined here
|
= note: `a` must be defined only once in the type namespace of this module
您可以通过增加一个级别来解决这个特殊情况:@H_801_3@
pub mod priMary {
pub mod a {
pub mod b {
pub struct A(pub i32);
}
}
}
pub mod import {
pub mod a {
pub use crate::priMary::a::*;
}
}
fn main() {
assert_eq!(import::a::b::A(42).0,42);
}
,
通配符导入为模块顶层的所有项目创建别名。@H_801_3@
在您的示例中,由于 priMary
仅包含一项 a
,因此通配符导入会创建一个别名 import::a
,它指代模块 priMary::a
。@H_801_3@
每当发生冲突时,显式命名的项目的优先级高于通过通配符导入的项目。实际上,您可以通过声明一个新项目或按名称从另一个模块导入它来隐藏通配符导入。@H_801_3@
每个 @H_869_5@mod 声明都声明了一个不同的模块。没有隐式合并模块中碰巧具有相同名称或别名的项目。@H_801_3@
以上是大佬教程为你收集整理的带有通配符使用声明的 Rust 子模块行为全部内容,希望文章能够帮你解决带有通配符使用声明的 Rust 子模块行为所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。