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

11

这段代码有效:

let x = Some(2);
println!("{:?}", x);

但这并不会:

let x = Some(2);
println!("{}", x);
5 | println!("{}", x);
  |                ^ std ::option::Option trait `std::fmt::Display` is 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个回答

15

{:?},或者说是具体的 ?,是由 Debug trait 使用的占位符。如果类型没有实现 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

实现Debug就可以解决这个问题:

#[derive(Debug)]
struct MyType {
    the_field: u32
}

fn main() {
    let instance = MyType { the_field: 5000 };
    println!("{:?}", instance);
}

输出为:MyType { the_field: 5000 }

您可以在文档中查看这些占位符/操作符的列表。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接