How to escape curly braces in a format string in Rust

十年热恋 提交于 2019-11-27 07:42:55

问题


I want to write this

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

But since curly braces have special meaning for formatting it's clear that I can't place the outer curly braces like that without escaping. So I tried to escape them.

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

Rust doesn't like that either. Then I read this:

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 "\{".

So I tried

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

But that's also not working. :-(


回答1:


You might be reading some out of date docs (e.g. for Rust 0.9)

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



来源:https://stackoverflow.com/questions/25569865/how-to-escape-curly-braces-in-a-format-string-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!