0%

Rust开发命令行工具 001_1 Hello World

使用cargo新建项目并运行

首先进入到开发目录中,

1
2
$ cargo new hello
Created binary (application) `hello` package

应该能在目录中看到以下内容了

1
2
3
4
5
6
$ cd hello
$ tree
.
├── Cargo.toml
└── src
└── main.rs

其中主要的main.rs文件内容是:

1
2
3
4
$ cat src/main.rs
fn main() {
println!("Hello, world!");
}

使用cargo run编译执行

1
2
3
4
5
$ cargo run
Compiling hello v0.1.0 (/private/tmp/hello)
Finished dev [unoptimized + debuginfo] target(s) in 1.26s
Running `target/debug/hello`
Hello, world!

Compiling hello v0.1.0 (/private/tmp/hello)
Finished dev [unoptimized + debuginfo] target(s) in 1.26s
Running target/debug/hello

  1. 前三行是cargo所做工作的信息, 包括编译, 完成时间, 运行内容等
  2. 最后的Hello, world!是程序的输出内容

如果你嫌弃cargo太过于啰嗦,你可以使用-q或者--quiet选项

1
2
$ cargo run --quiet
Hello, world!

使用ls命令来看一下目录里有什么

1
2
$ ls
Cargo.lock Cargo.toml src/ target/

其中,可执行程序被生成target/debug/hello, 可以直接执行

1
2
$ ./target/debug/hello
Hello, world!

cargo找到了main.rs文件,并将它编译成了程序,命名成hello.为什么使用了hello这个名字而不是main呢?
看一下cargo.toml, 它是项目的配置文件,你可以把它看成是mavenpom或者nodejspackage

1
2
3
4
5
6
7
8
9
cat Cargo.toml
[package]
name = "hello"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

name = “hello”

这是使用cargo创建工程时的名字, 所以可执行程序的名字也是这个

version = “0.1.0”

这是程序的版本号, 使用的是语义化版本, major.minor.patch

edition = “2021”

这是Rust的版本号

欢迎关注我的其它发布渠道