38
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rustのdbgマクロ

Last updated at Posted at 2018-10-04

Rustのデバッグ用機能のとしてRFC2361で新しくdbg!マクロが追加されたので使ってみました。

従来

printデバッグをしようとすると

#[derive(Debug)]
struct SomeStruct {
    pub a: usize,
    b: usize,
}


fn main() {
    let val = 1;
    eprintln!("{}", val);
    let some_struct = SomeStruct { a: 1, b: 2 };
    eprintln!("{:?}", some_struct);
}

こんな感じで{},{:?},{:#?}を使ってデバッグする必要がありました。
多少面倒な感じがありました。

dbg!

今回の追加されたdbg!マクロはこの煩わしさをいい感じに解決してくれました。
こんな感じのコードを実行すると

#![feature(dbg_macro)]

#[derive(Debug)]
struct SomeStruct {
    pub a: usize,
    b: usize,
}

#[derive(Debug)]
enum SomeEnum {
    A,
}

fn main() {
    dbg!(1);
    let val = 1;
    dbg!(val);
    dbg!("ABCD");
    dbg!(vec![1, 2, 3, 4]);
    let some_struct = SomeStruct { a: 1, b: 2 };
    dbg!(some_struct);
    dbg!(SomeEnum::A);
    let a = 1;
    let b = 2;
    let c = 3;
    let d = dbg!(a + b + c);
    dbg!(d);
    dbg!(a) + dbg!(b) + c;
}

}

ファイル名+行数でめっちょいい感じに出力してくれます。
うれしい!

[src/main.rs:15] 1 = 1
[src/main.rs:17] val = 1
[src/main.rs:18] "ABCD" = "ABCD"
[src/main.rs:19] vec![1 , 2 , 3 , 4] = [
    1,
    2,
    3,
    4
]
[src/main.rs:21] some_struct = SomeStruct {
    a: 1,
    b: 2
}
[src/main.rs:22] SomeEnum::A = A
[src/main.rs:26] a + b + c = 6
[src/main.rs:27] d = 6
[src/main.rs:28] a = 1
[src/main.rs:28] b = 2

補足

  • stderrで出力してくれます
  • println!と同様に所有権が渡されます。
    よってこのようなコードは動きません。
#![feature(dbg_macro)]

#[derive(Debug)]
struct SomeStruct {}
fn some_fn(_st: SomeStruct) {}
fn main() {
    let some_struct = SomeStruct {};
    dbg!(some_struct);
    some_fn(some_struct);
}

追記

nightly版(9/26~)でしか動きません。

38
20
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
38
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?