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。文章来源:https://www.toymoban.com/news/detail-488339.html
总结
本文通过一些实例介绍了{:?} vs {} 的区别,以及实现Display和Debug Trait文章来源地址https://www.toymoban.com/news/detail-488339.html
到了这里,关于Rust {:?} vs {} 知多少的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!