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

使用Rust工作区时出现未声明crate/module错误求助

Rust独立测试包无法识别依赖crate的问题

项目结构

-- project/
|
|-- Cargo.toml
|-- Cargo.lock
|-- src/ 
  |
  |-- main.rs
|-- crate1/
  |-- lib.rs
  |-- Cargo.toml
|-- tests
  |-- Cargo.toml
  |-- test.rs

配置文件内容

根目录Cargo.toml

...

[workspace]
members = [
  "crate1",
  "tests"
]

...

crate1/Cargo.toml

[package]
name = "crate1"

...

[lib]
path = "lib.rs"

...

tests/Cargo.toml

[package]
name = "tests"
version = "0.1.0"
edition = "2021"
publish = false

[dev-dependencies]
crate1 = { path = "../crate1" }

[[test]]
name = "crate1_test"
path = "crate1_test.rs"

[[test]]
name = "other_crate1_test"
path = "other_crate1_test.rs"

测试代码

// tests/crate1_test.rs
use crate1::random_func;

#[test]
fn random_func_test() {
    assert!(random_func());
}

错误信息(翻译后)

error[E0433]: 解析失败:未声明的包或模块crate1
--> tests/crate1_test.rs:1:5
|
1 | use crate1::random_func;
| ^^^^^^ 使用了未声明的包或模块crate1

想了解这个错误的更多信息,请尝试rustc --explain E0433。
error: 由于之前的错误,无法编译project-manager


解决方法

1. 调整依赖声明位置

tests包本身是用于测试的独立包,它需要直接依赖crate1,而非仅在开发阶段依赖。将tests/Cargo.toml中的[dev-dependencies]替换为[dependencies]:

[dependencies]
crate1 = { path = "../crate1" }

2. 检查配置文件名

确保tests目录下的配置文件名为Cargo.toml,而非拼写错误的Cargo.tom,文件名错误会导致Cargo无法加载包配置。

3. 确认被依赖函数的可见性

保证crate1/lib.rs中的random_func是公开的,需添加pub关键字:

pub fn random_func() -> bool {
    // 你的函数实现
    true
}

4. 重新运行测试

执行以下命令重新测试:

cargo test --package tests

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:20:25