Cargoの使い方について。
パッケージ作成
Rustの開発では、最初に以下のコマンドを実行して、プログラム開発に必要なディレクトリやファイル等を作成します。
cargo new [パッケージ名]
"Hello World"のパッケージ名を "helloworld"とすると、以下を実行します。
cargo new helloworldこれを実行すると以下のようになります。
$ cargo new helloworld
Created binary (application) `helloworld` package
正常に完了すると、現在のディレクトリに "helloworld" ディレクトリが作成され、Rust開発用ファイルが作成されます。
$ tree -a
.
└── helloworld
├── Cargo.toml
└── src
└── main.rs
2 directories, 2 files
Cargo.toml
Cargo.toml ファイルの中身は以下のようになります。
[package] name = "helloworld" version = "0.1.0" authors = ["user name <user@example.com>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies]authorsの名前とメールアドレスは、~/.gitconfig があれば、その[user]の名前とメールアドレスになります。
main.rs
main.rs ファイルの中身は以下のようになります。
fn main() {
println!("Hello, world!");
}
パッケージのビルド
ビルドは、パッケージのトップディレクトリで以下を実行します。 デフォルトでは、デバッグ情報を含んだ開発用ビルドになります。 デバッグ情報を含まないリリース用ビルドは、オプション--releaseを指定します。
cargo build
例
$ cargo build
Compiling helloworld v0.1.0 (/home/vagrant/rust/helloworld)
Finished dev [unoptimized + debuginfo] target(s) in 0.74s
ビルドが成功すると、以下のディレクトリ、ファイル構成になります。
$ tree -a
.
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
└── target
├── CACHEDIR.TAG
├── debug
│ ├── build
│ ├── .cargo-lock
│ ├── deps
│ │ ├── helloworld-129fc09c03e69dbb
│ │ └── helloworld-129fc09c03e69dbb.d
│ ├── examples
│ ├── .fingerprint
│ │ └── helloworld-129fc09c03e69dbb
│ │ ├── bin-helloworld
│ │ ├── bin-helloworld.json
│ │ ├── dep-bin-helloworld
│ │ └── invoked.timestamp
│ ├── helloworld
│ ├── helloworld.d
│ └── incremental
└── .rustc_info.json
9 directories, 14 files
リリースビルド
デフォルトでは、リリース用でなくデバッグ用のビルドになっています。 デバッグ情報などが無いリリース用ビルドを行う場合、以下を実行します。
cargo build --release
エラーがなければ以下のようになります。
$ cargo build --release
Compiling helloworld v0.1.0 (/home/vagrant/git/prog/rust/book/rust_2nd_edit/1.basic/helloworld)
Finished release [optimized] target(s) in 0.95s
リリース用実行ファイルは、以下になります。
target/release/[パッケージ名]パッケージ名がhelloworldの場合、以下がリリース用バイナリになります。
target/release/helloworldこれを実行すると、以下のようになります。
$ ./target/release/helloworld Hello, world!
実行
ビルドが成功したら、以下のコマンドでビルドしたパッケージを実行します。
cargo run
エラーがなければ以下のようになります。
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.05s
Running `target/debug/helloworld`
Hello, world!
実行ファイルを作成せずにプログラムのチェックを行う
Rustには、実行ファイルを作成せずに、プログラムをチェックするコマンドがあります。 そのコマンドは以下で、これは実行ファイルを作成しません。
cargo check
問題がなければ以下のようになります。
$ cargo check
Checking helloworld v0.1.0 (/home/vagrant/git/prog/rust/book/rust_2nd_edit/1.basic/helloworld)
Finished dev [unoptimized + debuginfo] target(s) in 2.37