此代码有效:
let x = Some(2);
println!("{:?}", x);
Run Code Online (Sandbox Code Playgroud)
但这不是:
let x = Some(2);
println!("{}", x);
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
..失败:
error[E0277]: the trait bound `MyType: std::fmt::Debug` is not satisfied
Run Code Online (Sandbox Code Playgroud)
#[derive(Debug)]
struct MyType {
the_field: u32
}
fn main() {
let instance = MyType { the_field: 5000 };
println!("{:?}", instance);
}
Run Code Online (Sandbox Code Playgroud)
哪个输出:MyType { the_field: 5000 }.
您可以在文档中看到这些占位符/运算符的列表.
| 归档时间: |
|
| 查看次数: |
1848 次 |
| 最近记录: |