在Rust," {}"之间的区别是什么?和" {:?}"在println中!?

时间:2016-12-15 03:42:40

标签: rust

此代码有效:

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`

为什么呢?那个背景下的:?是什么?

1 个答案:

答案 0 :(得分:5)

{:?},或者,具体而言,?,是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