LoginSignup
7
5

More than 3 years have passed since last update.

以外と多いcargoオプション

Posted at

今まで限られたオプションしか使ってなかったが、cargoコマンドのオプションは、以外と多かったので、まとめてみた。

  • 公式ドキュメント

  • 普段よく使うオプション

    • cargo new: 新規パッケージを作成する。
    • cargo update: Cargo.lockでロックされた依存クレートのバージョンをレジストリ(Crates.io)で公開されている最新バージョンに更新する。
    • cargo clean: targetディレクトリを削除する。
    • cargo build: ソースコードをビルド
    • cargo run: ビルドされたプログラムを実行する。
    • cargo test: テストを実行する。
    • cargo bench: ベンチマークプログラムを実行する。
    • cargo install: Rustバイナリーをインストールする。

普段あんまり使わなかった便利オプション(自分だけ?^^;)

をシチュエーション別にまとめてみた。

  • シチュエーション

    コードレビューする前にできるだけ指摘内容を減らしたい。

    • こんな時は、cargo clippyが便利
      コンパイラーは教えてくれない曖昧な表現などバグの原因になるような曖昧な記述についても警告してくれる
  • install

> rustup update
> cargo install -f clippy
  • run
> cargo clippy
  • source code
fn main(){
    let x = Some(1u8);
    match x {
        Some(y) => println!("{:?}", y),
        _ => ()
    }
}
  • cargo buildだと
> cargo build
   Compiling simple v0.1.0 (/home/AD/taehyung.kim/commit/simple)
    Finished dev [unoptimized + debuginfo] target(s) in 0.34s   
  • cargo clippyは
> cargo clippy                                           
    Checking simple v0.1.0 (/home/AD/taehyung.kim/commit/simple)                                        
warning: you seem to be trying to use match for destructuring a single pattern. Consider using `if let` 
 --> src/main.rs:3:5
  |
3 | /     match x {
4 | |         Some(y) => println!("{:?}", y),
5 | |         _ => (),
6 | |     }
  | |_____^ help: try this: `if let Some(y) = x { println!("{:?}", y) }`                                
  |
  = note: `#[warn(clippy::single_match)]` on by default                                                 
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_
match

    Finished dev [unoptimized + debuginfo] target(s) in 0.33s                                           
  • シチュエーション

Jsonをシリアライズ/デシリアライズできるクレートの名前とバージョンが思い出せない。

こんな時は、cargo searchが(ブラウザ要らずで)便利
crates.ioのクレートをキーワードだけで検索できる。

> cargo search json
json = "0.12.0"                           # JSON implementation in Rust
serde_json_experimental = "1.0.29-rc1"    # A JSON serialization file format
serde_json = "1.0.44"                     # A JSON serialization file format
jsonpath_lib = "0.2.3"                    # It is JsonPath engine written in Rust. it provide a similar A
PI interface in Webassem\u2026
assert-json-diff = "1.0.1"                # Easily compare two JSON values and get great output
json_in_type = "1.1.1"                    # a library for fast json serialization
json_macros = "0.3.2"                     # Convenience macros for constructing JSON objects from literal
s. 
jql = "2.4.8"                             # A JSON query language CLI tool
json_typegen = "0.4.0"                    # Procedural macro that generates Rust types from JSON samples
cddl = "0.3.18"                           # Parser for the Concise data definition language (CDDL)
... and 1327 crates more (use --limit N to see more)
  • シチュエーション
    頻繁にソースコードを修正し、ビルドする。

こんな時は、cargo watchが便利
ソースコードの変更を検知して自動でビルドしてくれる

  • install
> cargo install cargo-watch
  • build
> cargo watch
  • build & test
cargo watch -x test
  • シチュエーション
    Cargo.tomlに追加したクレートの依存クレートが知りたい。

こんな時は、cargo treeが便利
クレートの依存関係をツリー形式で表示してくれる

> cargo tree                        
racer v2.0.3
├── clap v2.19.1
│   ├── ansi_term v0.9.0
│   ├── bitflags v0.7.0
│   ├── libc v0.2.18
│   ├── strsim v0.5.2
│   ├── term_size v0.2.1
│   │   └── libc v0.2.18 (*)
│   ├── unicode-segmentation v0.1.3
│   ├── unicode-width v0.1.3
│   └── vec_map v0.6.0
...
  • シチュエーション
    マクロで生成されるコードをみたい

こんな時は、cargo expandが便利
マクロがソースコードに展開された後のコートを表示してくれる

  • source code
#[derive(Debug, Clone)]
struct Foo<T>(T);

fn bar() {
    println!("{}", 3.14);
}
  • cargo expand
#![feature(prelude_import)]
#![no_std]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std as std;
struct Foo<T>(T);
#[automatically_derived]
#[allow(unused_qualifications)]
impl<T: ::std::fmt::Debug> ::std::fmt::Debug for Foo<T> {
    fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        match *self {
            Foo(ref __self_0_0) => {
                let mut builder = __arg_0.debug_tuple("Foo");
                let _ = builder.field(&&(*__self_0_0));
                builder.finish()
            }
        }
    }
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl<T: ::std::clone::Clone> ::std::clone::Clone for Foo<T> {
    #[inline]
    fn clone(&self) -> Foo<T> {
        match *self {
            Foo(ref __self_0_0) => Foo(::std::clone::Clone::clone(&(*__self_0_0))),
        }
    }
}

fn bar() {

    ::io::_print(::std::fmt::Arguments::new_v1(
        {
            static __STATIC_FMTSTR: &'static [&'static str] = &["", "\n"];
            __STATIC_FMTSTR
        },
        &match (&3.14,) {
            (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0, ::std::fmt::Display::fmt)],
        },
    ));
}
7
5
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
7
5