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

标签 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`

为什么?什么是 :? 在那种情况下?

最佳答案

{:?},或者更具体地说,?,是 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 .

关于rust - 在 Rust 中,println! 中的 "{}"和 "{:?}"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41156082/

相关文章:

rust - 如何将命令 stdout 保存到文件?

rust - 从 Rust 填充 C 字符串指针的正确方法是什么?

rust - 同时修改切片/集合的多个元素

rust - 如何使用具有自引用结构的 Pin 结构?

docker - SSL 证书验证适用于 Docker,而不适用于 Kubernetes

variables - 为什么我必须为 "const"变量指定类型而不是 "let"变量?

rust - 在没有 map_err 的情况下将 and_then 与不同的结果错误类型一起使用

rust - 什么是 Rust 系统测试?

generics - 如何在Rust中实现装饰器?

vector - 在不重新分配的情况下将 Vec 转换为 FFI 的正确方法是什么?