我如何告诉 Cargo 构建 main.rs 以外的文件? [英] How do I tell Cargo to build files other than main.rs?

查看:32
本文介绍了我如何告诉 Cargo 构建 main.rs 以外的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的目录结构:

lowks@lowkster ~/src/rustlang/gettingrusty $ tree ..├── 货物锁├── Cargo.toml├── foo.txt├── src│ ├── boolean_example.rs│ ├── function_goodbye_world.rs│ ├── listdir.rs│ ├── looping.rs│ ├── main.rs│ ├── pattern_match.rs│ └── write_to_file.rs└── 目标├──构建├── deps├── 例子├── 生锈└── 本土6个目录,11个文件

当我运行 'cargo build' 时,它似乎只构建 main.rs.我应该如何更改 Cargo.toml 以构建其余文件?

解决方案

Rust 编译器同时编译所有文件以构建 crate,它可以是可执行文件或库.要将文件添加到您的 crate,请将 mod 项添加到您的 crate 根目录(此处为 main.rs)或其他模块:

mod boolean_example;mod function_goodbye_world;mod列表目录;模式循环;mod pattern_match;mod write_to_file;

要从您的 crate 根访问另一个模块中定义的项目,您必须使用模块名称限定该项目.例如,如果您在 looping 模块中有一个名为 foo 的函数,则必须将其引用为 looping::foo.

您还可以添加 use 语句来导入模块范围内的名称.例如,如果你加上use looping::foo;,那么你就可以直接使用foo来引用looping::foo.>

有关更多信息,请参阅 将模块分成不同的文件Rust 编程语言.

Here is my directory structure:

lowks@lowkster ~/src/rustlang/gettingrusty $ tree .
.
├── Cargo.lock
├── Cargo.toml
├── foo.txt
├── src
│   ├── boolean_example.rs
│   ├── function_goodbye_world.rs
│   ├── listdir.rs
│   ├── looping.rs
│   ├── main.rs
│   ├── pattern_match.rs
│   └── write_to_file.rs
└── target
    ├── build
    ├── deps
    ├── examples
    ├── gettingrusty
    └── native

6 directories, 11 files

When I run 'cargo build', it seems to only build main.rs. How should I change Cargo.toml to build the rest of the files too?

解决方案

The Rust compiler compiles all the files at the same time to build a crate, which is either an executable or a library. To add files to your crate, add mod items to your crate root (here, main.rs) or to other modules:

mod boolean_example;
mod function_goodbye_world;
mod listdir;
mod looping;
mod pattern_match;
mod write_to_file;

To access items defined in another module from your crate root, you must qualify that item with the module name. For example, if you have a function named foo in module looping, you must refer to it as looping::foo.

You can also add use statements to import names in the module's scope. For example, if you add use looping::foo;, then you can just use foo to refer to looping::foo.

For more information, see Separating Modules into Different Files in The Rust Programming Language.

这篇关于我如何告诉 Cargo 构建 main.rs 以外的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆