Rust {:?} vs {} 知多少

Rust {:?} vs {} 知多少

{} 指示符

{} 需要实现std::fmt::Display

{:?} 指示符

{:?} 需要实现std::fmt::Debug

案例展示

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

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

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

编译报错:

error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`

提示我们没有实现Display trait


改成如下代码:

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

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

编译报错:

error[E0277]: `Rectangle` doesn't implement `Debug`

提示没有实现Debug trait


通过上面报错提示,我们在实现struct时候要根据自己的需要来实现Display或者Debug Trait。

自定义实现Display trait

use std::fmt;
struct Rectangle {
    width: u32,
    height: u32,
}
impl fmt::Display for Rectangle{
    // This trait requires `fmt` with this exact signature.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Write strictly the first element into the supplied output
        // stream: `f`. Returns `fmt::Result` which indicates whether the
        // operation succeeded or failed. Note that `write!` uses syntax which
        // is very similar to `println!`.
        write!(f, "{} {}", self.width,self.height)
    }
}
fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

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

输出如下:

rect1 is 30 50

Debug Trait

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

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

输出如下:

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

一般我们可以通过#[derive(Debug)] 在编译阶段,编译器帮忙我们自动实现Debug trait。

总结

本文通过一些实例介绍了{:?} vs {} 的区别,以及实现Display和Debug Trait

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值