我在学习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);
}
}
上面的代码运行结果如下: