rust打印自定义对象

没错,我也在学习rust语言😋

背景

我在学习rust的时候,在想,rust如何像python一样,可以打印一个对象呢?

就像是python里面的__str__或者__repr__

代码

摸索


struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}


fn main() {
    let mut arr2 = vec![
        User {
            email: String::from("😋@.com"),
            username: String::from("小黄"),
            active: false,
            sign_in_count: 1,
        },
    ];
    arr2.push(User {
        email: String::from("🙃@.com"),
        username: String::from("小李"),
        active: true,
        sign_in_count: 3,
    });
// 打印一下内容
    for value in arr2 {
        println!("{:?}", value);
    }
}

上面代码运行,发现不通过:

我在println!里面都加了:?怎么还不通过。具体我也不清楚。

后来我在想:rust是否可以像python那样,只要对对象实现了__str__或者__repr__方法,就可以打印了。

果然,去谷歌了一下,就找到了答案:

解决办法

我参考了这个链接:https://stackoverflow.com/questions/30253422/how-to-print-structs-and-arrays

User实现了一个方法: std::fmt::Display
完整代码如下:


struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

impl std::fmt::Display for User {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "show result---> active: {}, username: {}, email: {}, count: {}", self.active, self.username, self.email, self.sign_in_count)
    }
}

fn main() {
    let mut arr2 = vec![
        User {
            email: String::from("😋@.com"),
            username: String::from("小黄"),
            active: false,
            sign_in_count: 1,
        },
        User {
            email: String::from("😘@.com"),
            username: String::from("小花"),
            active: true,
            sign_in_count: 2,
        },
    ];
    arr2.push(User {
        email: String::from("🙃@.com"),
        username: String::from("小李"),
        active: true,
        sign_in_count: 3,
    });
// 打印一下内容
    for value in arr2 {
        println!("{}", value);
    }
}


上面的代码运行结果如下:

参考链接

  1. https://stackoverflow.com/questions/30253422/how-to-print-structs-and-arrays
  2. https://kaisery.github.io/trpl-zh-cn/ch08-01-vectors.html
  3. https://kaisery.github.io/trpl-zh-cn/ch05-01-defining-structs.html

个人感受

  1. 目前主要是使用python和R。也在学习一点点C++,rust。
  2. 感觉这个rust写起来和python差不多呀,尤其是构建数据结构的时候(目前还没对rust的模式设计了解过)。rust写起来也很轻松,感觉不怎么像是c++这么“拗口”。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuanzhoulvpi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值