12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

cargo exampleコマンドのススメ

Last updated at Posted at 2021-11-07

cargoとは

Cargoは、Rustのビルドシステム兼、パッケージマネージャです。(参照)

exampleとは

パッケージ内のexamplesフォルダ内のソースコードを実行するサブコマンドです。

cargoで想定されるパッケージレイアウト

.
├── <benches>
│   └── <benches.rs>
├── <examples>
│   └── <examples.rs>
├── src
│   ├── <bin>
│   │   └── <another_executable.rs>
│   ├── <lib.rs>
│   └── main.rs
├── <tests>
│   └── <tests.rs>
├── <Cargo.lock>
└── Cargo.toml

<>で囲ったファイル又はフォルダは、cargo newコマンドでは作られません。

フォルダ名について

Cargoで作成したプロジェクトフォルダには、
あらかじめ規約が設けられています。

例えば、benches bin examples testsという
4種のフォルダ名には、暗黙的に役割が与えられています。

これらのフォルダが存在している場合は、
下記のオプションを使うことでフォルダ内の
Rustファイル(.rs)に対する操作が簡単に行えます。

cargo run --example [実行したいファイル名(拡張子を除く)]    # examplesフォルダ 
          --bin     [実行したいファイル名(拡張子を除く)]    # binフォルダ

cargo test    # testsフォルダ内のテスト実行

cargo bench   # benchesフォルダ内のベンチマーク実行

最後に伝えたいこと

ソースファイルを沢山作って実験する際は、examplesフォルダに入れて、

cargo run --example [実行したいファイル名(拡張子を除く)]

で実行を行った方がmain関数の書かれた沢山のソースファイルを
1プロジェクト内に共存できるので便利だと思います。

追記.examplesフォルダ内のファイルではなく、プロジェクトを実行したい場合

プロジェクトのルートフォルダにあるCargo.tomlファイルに
membersを追加することでプロジェクトを参照可能になります。

.
├── Cargo.toml <-- これにmembersを追記
├── examples
│   └── example-project <-- cargo new等で作成した別プロジェクトを実行できるようになる
│       ├── Cargo.toml
│       └── src
│           └── main.rs
└──src
    └── main.rs
Cargo.toml
[workspace]
members = ["examples/*"]

example-projectの実行コマンド

cargo run --package example-project
12
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?