gpt4 book ai didi

What does {:?} mean in a Rust format string?(在铁锈格式字符串中,{:?}是什么意思?)

转载 作者:bug小助手 更新时间:2023-10-26 21:34:22 33 4
gpt4 key购买 nike



I found out that {:?} prints an entire array in Rust. I want to know what is it called and how exactly it works. Is it only limited to printing arrays or could it also be used elsewhere for other purposes?

我发现{:?}在Rust中打印整个数组。我想知道它叫什么,它到底是怎么工作的。它是否仅限于打印阵列,或者也可以用于其他目的?


更多回答
优秀答案推荐

This is explained (along with the rest of the formatting syntax) in the std::fmt documentation.

在std::fmt文档中解释了这一点(以及其余的格式化语法)。



{...} surrounds all formatting directives. : separates the name or ordinal of the thing being formatted (which in this case is omitted, and thus means "the next thing") from the formatting options. The ? is a formatting option that triggers the use of the std::fmt::Debug implementation of the thing being formatted, as opposed to the default Display trait, or one of the other traits (like UpperHex or Octal).

{...}包含所有格式化指令。:将要格式化的事物的名称或序号(在本例中省略,因此表示“下一事物”)与格式化选项分开。那个?是一个格式化选项,它触发正在格式化的对象的std::fmt::调试实现,而不是默认的显示特性或其他特性之一(如UpperHex或Octal)。



Thus, {:?} formats the "next" value passed to a formatting macro, and supports anything that implements Debug.

因此,{:?}格式化传递给格式化宏的“NEXT”值,并支持实现Debug的任何内容。



The Debug trait is one of the most commonly used in Rust.
It allows you to format the output in a programmer-facing, debugging context. The way you typically use it is like this:

Debug特性是Rust中最常用的特性之一。它允许您在面向程序员的调试上下文中格式化输出。通常使用它的方式如下所示:


let v = vec![1, 2, 3];
let s = format!("{:?}", v);

Also, as of Rust 1.58 you can Debug-format a variable by putting it right after the opening curly bracket, like this:

此外,从Rust 1.58开始,您可以通过将变量放在左花括号后面进行调试格式化,如下所示:


let s = format!("{v:?}");

If you want to Debug-format a custom type, such as a struct, you can simply use derive like this:

如果要调试格式化自定义类型(如结构),只需使用如下所示的派生:


#[derive(Debug)]
struct Person {
name: String,
age: u8,
}

更多回答

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com