字符串格式 – 如何在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)

但这也不行. 🙁

您可能会阅读一些过时的文档(例如,用于生锈0.9)

用于格式化生锈0.11的字符串的current way是逃避{和}与另一个{或}

   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 }}.

翻译自:http://stackoverflow.com/questions/25569865/how-to-escape-curly-braces-in-a-format-string-in-rust

转载注明原文:字符串格式 – 如何在Rust中的格式字符串中转出大括号