Rust构建自己的第一个项目

几个核心命令:

cargo new xxx:用于新建项目

cargo build:用于在Cargo.toml中添加dependencies进行依赖的下载和编译

cargo run:用于运行

新建项目

在目录下输入下列指令,例如要构建一个叫做hello-rust的项目

1
cargo new hello-rust

image-20240717224533358.png

Cargo 已经帮我们创建好默认项目了,还创建了个git的本地仓库,还有一些配置文件, src/main.rs 为编写应用代码的地方。

运行项目

使用cargo run命令运行

1
cargo run

image-20240717224940931.png

可以看到会经历一个编译的过程后,打印出Hello,world!信息

编写Hello-Rust

Cargo.toml文件是一个管理项目配置的文件,包括项目依赖等相关配置

添加配置在dependencies中:

image-20240717225346375.png

在命令行中运行:

1
cargo build

image-20240717225528135.png

可以看到除了我们自定义添加的ferris-say版本的依赖,还会自动添加好依赖的依赖

接下来就在 src/main.rs 中写入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
use ferris_says::say; // from the previous step
use std::io::{stdout, BufWriter};
fn main() {
let stdout = stdout();
let message = String::from("Hello fellow Rustaceans!");
let width = message.chars().count();

let mut writer = BufWriter::new(stdout.lock());
say(message.as_bytes(), width, &mut writer).unwrap();
}


再执行

1
cargo run

image-20240717230124205.png