此代码有效:
let x = Some(2);
println!("{:?}", x);
但这不是:
let x = Some(2);
println!("{}", x);
5 | println!("{}", x);
| ^ trait `std::option::Option: std::fmt::Display` not satisfied
|
= note: `std::option::Option` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
= note: required by `std::fmt::Display::fmt`
为什么?什么是 :?
在那种情况下?
{:?}
,或者更具体地说,?
,是 Debug
特征使用的占位符。如果该类型未实现 Debug
,则在格式字符串中使用 {:?}
会中断。
例如:
struct MyType {
the_field: u32
}
fn main() {
let instance = MyType { the_field: 5000 };
println!("{:?}", instance);
}
..失败:
error[E0277]: the trait bound `MyType: std::fmt::Debug` is not satisfied
Implementing Debug
though, fixes that :
#[derive(Debug)]
struct MyType {
the_field: u32
}
fn main() {
let instance = MyType { the_field: 5000 };
println!("{:?}", instance);
}
输出:MyType { the_field: 5000 }
。
您可以看到这些占位符/运算符的列表 in the documentation .