gpt4 book ai didi

string-formatting - 如何在 Rust 的格式字符串中转义大括号

转载 作者:行者123 更新时间:2023-11-29 07:40:21 33 4
gpt4 key购买 nike

我想写这个

write!(f, "{ hash:{}, subject: {} }", self.hash, self.subject)

但是由于花括号对格式化有特殊意义,所以很明显我不能在不转义的情况下那样放置外部花括号。所以我想逃避他们。

write!(f, "\{ hash:{}, subject: {} \}", self.hash, self.subject)

Rust 也不喜欢这样。然后我读到这个:

The literal characters {, }, or # may be included in a string by preceding them with the \ character. Since \ is already an escape character in Rust strings, a string literal using this escape will look like "\{".

所以我试过了

write!(f, "\\{ hash:{}, subject: {} \\}", self.hash, self.subject)

但这也行不通。 :-(

最佳答案

您可能正在阅读一些过时的文档(例如 Rust 0.9)

从 Rust 1.0 开始,the way to escape { and } is with another { or }

write!(f, "{{ hash:{}, subject: {} }}", self.hash, self.subject)

The literal characters { and } may be included in a string by preceding them with the same character. For example, the { character is escaped with {{ and the } character is escaped with }}.

关于string-formatting - 如何在 Rust 的格式字符串中转义大括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25569865/

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