我正在学习 Rust,并决定编写一个简单的客户端/服务器程序。客户端和服务器都将使用我已经编写的一个非常简单的模块。知道这段代码可能会增长,为了清晰起见,我决定将我的源代码分开。现在,我当前的层次结构如下所示:
├── Cargo.lock
├── Cargo.toml
├── README.md
├── src
│ ├── client
│ │ └── main.rs
│ ├── common
│ │ ├── communicate.rs
│ │ └── mod.rs
│ ├── lib.rs
│ └── server
│ └── main.rs
Many of the当 main.rs
位于项目根目录中时,我在 Stack Overflow 和网络上找到的示例提供了很好的示例。不幸的是,我正在尝试做一些不同的事情,如上所示。
communicate.rs
包含我编写的所有网络代码。最后,我将在此处添加其他 Rust 文件,并将它们的 public mod
语句包含在 mod.rs
中。目前 common/mod.rs
我只有
pub mod 通信;
只关注 client
文件夹,我只有 main.rs
,如图所示。文件“头”列表
extern crate common;
use std::thread;
use std::time;
use std::net;
use std::mem;
use common::communicate;
pub fn main() {
// ...
}
除了基本的 [package]
部分,我在 Cargo.toml
中只有
[[bin]]
name = "server"
path = "src/server/main.rs"
[[bin]]
name = "client"
path = "src/client/main.rs"
当我尝试构建客户端二进制文件时,编译器提示找不到 common
crate。
$ cargo build
Compiling clientserver v0.1.0 (file:///home/soplu/rust/RustClientServer)
client/main.rs:1:1: 1:21 error: can't find crate for `common` [E0463]
client/main.rs:1 extern crate common;
^~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
error: Could not compile `clientserver`.
To learn more, run the command again with --verbose.
我认为这是因为它正在 client/
文件夹中寻找一个通用的 crate。当我尝试使用 mod
语句而不是 extern crate
语句时,我遇到了同样的问题。
use std::thread;
use std::time;
use std::net;
use std::mem;
mod common;
给我:
client/main.rs:6:5: 6:11 error: file not found for module `common`
client/main.rs:6 mod common;
^~~~~~
client/main.rs:6:5: 12:11 help: name the file either common.rs or common/mod.rs inside the directory "client"
我也试过(使用extern crate...
)在client
中添加一个lib.rs
,其内容是 pub mod common;
但我仍然遇到与第一个相同的错误。
我发现一个潜在的解决方案可以像 this project 一样建模,但这需要在每个文件夹中都有一个 Cargo.toml
,这是我想避免的。
我觉得我很接近,但缺少一些东西。
最佳答案
您现在没有将 common
构建为箱子。正在构建的箱子是库 clientserver
(库的默认名称是包名称)和二进制文件 client
和 server
。
通常,extern crate clientserver;
应该可以工作。但是,如果您想以不同的方式命名您的库,您可以通过在 [lib]
section in Cargo.toml 中指定不同的名称来实现。 .在此部分中,您还可以为库的主要源文件指定不同的源路径。在你的情况下,它可能会更好,否则你最终会得到一个名为 common
的 crate ,它的所有内容都将在一个名为 common
的模块中,所以你必须以 common::common::foo
的形式访问所有内容。例如,通过将此添加到您的 Cargo.toml:
[lib]
name = "common"
path = "src/common/lib.rs"
您可以将 src/lib.rs
和 src/common/mod.rs
合并到 src/common/lib.rs
中。然后,extern crate common;
应该可以在您的二进制文件中工作。
关于rust - 从多个非根二进制文件导入非根模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39692942/