走进 Rust:打印结构体字段

Rust About 1,017 words

定义结构体

struct Rectangle {
    width: u32,
    height: u32,
}

打印结构体

使用{}打印会报错。

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };

    println!("rect1 is {}", rect1);
}

提示信息:

= help: the trait `std::fmt::Display` is not implemented for `Rectangle`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead

使用{:?}{:#?}打印结构体中的字段信息。

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };

    println!("rect1 is {:?}", rect1);
}

提示信息:

= help: the trait `std::fmt::Debug` is not implemented for `Rectangle`
= note: add `#[derive(Debug)]` or manually implement `std::fmt::Debug`

结构体上增加#[derive(Debug)]

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };

    println!("rect1 print by :?, {:?}", rect1);

    println!("rect1 print by :#?, {:#?}", rect1);
}

输出:

rect1 print by :?, Rectangle { width: 30, height: 50 }
rect1 print by :#?, Rectangle {
    width: 30,
    height: 50,
}
Views: 8,168 · Posted: 2020-07-09

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh