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

标签 string-formatting rust

我想写这个

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/

相关文章:

java - 格式化字符串java

rust - 争论要求 _ 是为 'static 借用的 - 我该如何解决这个问题?

rust - 在 Optional 中展开结果

java - 使用 %1$s 时格式化文件名

Python 3.2 - 连接和字符串格式化行为不符合预期

python - 如何使用字符串格式函数打印对象的表示形式?

c# - String.Format 格式化没有美分的货币的方法

rust - 为自定义特征提供一揽子特征实现

rust - 删除 crate 功能

rust - 在本地存储对象后无法确定处理引用的生命周期