mkdir -p projects/hello_world/
cd projects/hello_world
main.rs文件
fn main() {
println!("hello, world!");
}
编译和运行
rustc main.rs
./main
格式化:rustfmt
Cargo 是 Rust 的构建系统和包管理器。
构建如下:
cargo new hello_world --bin
--bin
为默认参数,表示构建二进制程序。可选--lib
表示构建库。
nsfoxer@nsfoxer-pc ~/temp> cargo new hello_world --bin
Created binary (application) `hello_world` package
nsfoxer@nsfoxer-pc ~/temp> tree hello_world
hello_world
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
cargo会同时构建git项目。使用--vcs none
禁用git存储。
编译:
cargo build
将获取所有依赖项。
nsfoxer@nsfoxer-pc ~/t/hello_world> tree .
.
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
└── target
├── CACHEDIR.TAG
└── debug
├── build
├── deps
│ ├── hello_world-efb3cc30327658a6
│ └── hello_world-efb3cc30327658a6.d
├── examples
├── hello_world
├── hello_world.d
└── incremental
└── hello_world-2bu9x4t5793bs
├── s-g1qy781nco-1nkogqh-2hbtkajf7iavr
│ ├── 1afbzx1y0x1dbpio.o
│ ├── 1ko7w99wy4kz2chh.o
│ ├── 28cobucdo6rhinaa.o
│ ├── 2goevba305ege8v6.o
│ ├── 4d0psjpawt67vlja.o
│ ├── 5byta3abs29cbrhj.o
│ ├── 5dygtqqmhu41ip90.o
│ ├── dep-graph.bin
│ ├── gfq0hw1bwbsq84d.o
│ ├── query-cache.bin
│ └── work-products.bin
└── s-g1qy781nco-1nkogqh.lock
9 directories, 20 files
Cargo.lock
包含依赖相关信息。使用--release
开启编译优化。
Caogo.toml
包含项目的各种元信息。
运行:
./target/debug.hello_world
可以使用cargo run
进行编译和运行。
可以使用cargo check
进行代码检查。
cargo允许Rust项目声明其各种依赖,并保证始终可重复构建。
rustc
或其他工具进行构建;crates.io是 Rust 社区的中央存储库,用作发现和下载包的位置。cargo
默认配置为,使用它来查找请求的包。
[dependencies]
time = "0.1.12"
regex = "0.1.41"
cargo build
将会获取依赖。如果regex
在crates.io上更新了,在我们选择cargo update
之前,我们仍会使用相同的版本进行构建.
.
├── Cargo.lock
├── Cargo.toml
├── benches # 基准测试
│ └── large-input.rs
├── examples # 示例
│ └── simple.rs
├── src
│ ├── bin # 其他可执行文件
│ │ └── another_executable.rs
│ ├── lib.rs # 库文件
│ └── main.rs # 可执行文件
└── tests # 集成测试
└── some-integration-tests.rs
Cargo.toml
是从广义上描述你的依赖,并由你编写.Cargo.lock
包含有关您的依赖项的确切信息。它由 Cargo 维护,不应手动编辑.Cargo.lock
放置在你的.gitignore
Cargo.lock
位于git
管理下。[dependencies]
rand = { git = "https://github.com/rust-lang-nursery/rand.git", rev = "9f35b8e" }
如上,依赖于github上的项目,当未指定其他信息时默认依赖github上的最新版本。例子中rev
指定github的版本。
Cargo.lock
会记录项目第一次构建时依赖版本,此时不需要进行手动添加加具体版本。
当我们准备选择,更新库的版本时,Cargo 会自动重新计算依赖关系,并为我们更新内容:
$ cargo update # updates all dependencies
$ cargo update -p rand # updates just “rand”
cargo test
:会查找src
和tests
的测试
原文:https://www.cnblogs.com/nsfoxer/p/15196551.html