Compiler errors 为什么将同一文件中的同一结构包含到多个板条箱中会导致类型不匹配错误?
我创建了以下文件结构:Compiler errors 为什么将同一文件中的同一结构包含到多个板条箱中会导致类型不匹配错误?,compiler-errors,rust,Compiler Errors,Rust,我创建了以下文件结构: mod_测试/src/ |-梅因 |-a_.rs模块 |-图书馆 a_模块.rs pub struct A {} mod a_module; pub fn run(s: a_module::A) {} extern crate mod_test; mod a_module; fn main() { let b: a_module::A b = a_module::A {}; mod_test::run(b); } lib.rs pub stru
mod_测试/src/
|-梅因
|-a_.rs模块
|-图书馆
a_模块.rs
pub struct A {}
mod a_module;
pub fn run(s: a_module::A) {}
extern crate mod_test;
mod a_module;
fn main() {
let b: a_module::A b = a_module::A {};
mod_test::run(b);
}
lib.rs
pub struct A {}
mod a_module;
pub fn run(s: a_module::A) {}
extern crate mod_test;
mod a_module;
fn main() {
let b: a_module::A b = a_module::A {};
mod_test::run(b);
}
main.rs
pub struct A {}
mod a_module;
pub fn run(s: a_module::A) {}
extern crate mod_test;
mod a_module;
fn main() {
let b: a_module::A b = a_module::A {};
mod_test::run(b);
}
lib文件中run
函数的参数类型显然与b
is相同(除了名称空间,在这两种情况下都是A
struct)。由于run
导入到另一个命名空间中,编译器告诉我存在类型不匹配:
expected: modTest::a_module::A -- got: a_module::A
我知道如何纠正这种行为,但为什么要这样做
为什么编译器看不到结构是完全相同的,因为它引用的是完全相同的文件?就编译器而言,您使用的不是相同的类型。锈有名义类型,而不是结构类型。您可能熟悉TypeScript等语言的结构类型
除了名称空间
名称空间(包括板条箱)是使类型唯一的一部分。您已在不同的板条箱中多次导入同一文件。这与在不同的模块中使用相同的结构没有什么不同:
mod a {
struct A;
}
mod b {
struct A;
}
这些不应是相同的类型
它们是同一个文件这一事实对编译器来说并不重要。如果真是这样的话,符号链接和硬链接会出现一些奇怪的问题
重要的是您将类型放置在板条箱和模块层次结构中的什么位置
另见: