You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在多个Crate中引入同一文件的同一Struct会出现类型不匹配错误?

Why does Rust throw a type mismatch for identical-looking A structs?

Great question—this is a super common gotcha when you're getting started with Rust modules and crates! The short answer is: Even though your two A structs look identical, they're actually completely separate types in Rust's eyes.

Let me break down exactly why this happens with your code:

First, let's look at how Rust treats your project files:

  • Your lib.rs defines a library crate (mod_test), with its own a_module containing the A struct. When you write pub fn run(s: a_module::A) {}, that A is tied to the library crate's module hierarchy.
  • Your main.rs is a binary crate (separate from the library, even though they live in the same project directory). When you add mod a_module; here, you're creating a new, local module in the binary crate, with its own independent A struct.

Rust doesn't care that the structs have the same name or identical definitions—what matters is their full path (crate + module hierarchy). The A from mod_test::a_module and the A from your binary's local a_module are as different as String and Vec<u8> to the compiler.

How to fix this

The simplest fix is to stop redefining the module in main.rs and instead use the A struct from your library crate directly:

Modify your main.rs like this:

extern crate mod_test;
// Import the library's A struct into our scope
use mod_test::a_module::A;

fn main() {
    let b: A = A {};
    mod_test::run(b);
}

Now b is an instance of the exact same A type that the run function expects, so the type mismatch error will disappear.

Another way to think about it: Think of crates as separate "worlds" for types. A type defined in one crate can't be passed to a function expecting a type from another crate unless they're explicitly the same type (like imported via use).

Key takeaway

Rust's type system enforces strict uniqueness based on a type's full path. Even identical-looking structs in different modules (or different crates) are distinct types. This prevents accidental naming conflicts and keeps your code's type relationships clear.

内容的提问来源于stack exchange,提问作者KuSpa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:02:29