Rust语言入门(4)—— Hello world& Cargo
Helloworld
上一篇我们完成了Rust环境的搭建,本章我们会介绍如何创建Rust的第一个工程,以及后续如何使用cargo构建项目
1. 编写运行Hello world
(1) 创建一个hello_world文件夹,然后创建hello_world.rs
mkdir hello_world
cd hello_world
touch hello_world.rs
(2) 打开hello_world.rs, 并输入如下代码:
fn main(){
println!("Hello, world!");
}
(3) 编译及运行
rustc hello_world.rs
./hello_world
至此,我们已经完成了第一个rust程序的编译及运行,非常简单,我就不增加我编译的图片了。
2. 使用Cargo创建一个项目
(1)创建项目
cargo new hello_cargo
cd hello_cargo
在hello_cargo下会新增如下文件:

(2)打开Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
Cargo使用TOML作为标准的配置格式。
首行文本中的[package]是一个区域标签,它表明接下来的语句会被用于配置当前的程序包。 [dependencies]同样也是区域标签
(3)打开src
src下只有一个main.rs
fn main() {
println!("Hello, world!");
}
3. 使用Cargo构建和运行项目
(1)构建
cargo build

这里构建后,产生的结果在target/debug目录下。
(2)运行
./target/debug/hello_cargo

(3) cargo run
cargo run命令可以同时完成编译和执行

这里默认都是debug模式,若是发布项目时,使用
cargo run --release
(4)cargo check
使用该命令可以快速检查当前的代码是否可以通过编译

好啦,至此,我们已经在Rust上卖出第一步啦,希望后续一步一个脚印,完成Rust星际之旅。