走进Rust:打印结构体字段

Rust大约 1016 字

定义结构体

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,
}
阅读 189 · 发布于 2020-07-09

————        END        ————

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

昵称:
随便看看换一批