1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rustの'#[derive(Debug)]'ってなんですのん

Posted at

#[derive(Debug)] とは

enum,トレイトの説明とかで当たり前のように出てくるこれは何なのか改めて調べてみた

使い方

例えば、Personの構造体を作って、開発中にそれの中身を確認したいなって時に使います

逆に#[derive(Debug)]が無いとコンパイラエラーで中身は確認できません。

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
}

fn main() {
    let person = Person {
        name: String::from("Alice"),
        age: 30,
    };
    println!("{:?}", person); // ここで中身を確認したい

    println!("-----------------------");
    println!("{}", person.name);
    println!("{}", person.age);
}

Person { name: "Alice", age: 30 }
--------------------
Alice
30

2種類の表示方法

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
}

fn main() {
    let person = Person {
        name: String::from("Alice"),
        age: 30,
    };

    println!("{:?}", person); // Debug formatting
    println!("------------------------------------");
    println!("{:#?}", person); // Pretty print
}

{:?}でフォーマットなしで出力します。
{:#?}でフォーマットありで出力します。

Person { name: "Alice", age: 30 }
------------------------------------
Person {
    name: "Alice",
    age: 30,
}

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?