如何在 Rust 中的格式字符串中转义花括号 [英] How to escape curly braces in a format string in Rust

查看:41
本文介绍了如何在 Rust 中的格式字符串中转义花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写这个

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

但是由于大括号对于格式化有特殊的意义,很明显我不能像那样放置外部大括号而不进行转义.所以我试图逃避他们.

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

Rust 也不喜欢那样.然后我读了这个:

<块引用>

文字字符 {、} 或 # 可以通过在它们前面加上 \ 字符来包含在字符串中.由于 \ 已经是 Rust 字符串中的转义字符,因此使用此转义的字符串文字将类似于\{".

所以我尝试了

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

但这也行不通.:-(

解决方案

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

从 Rust 1.0 开始,转义 {} 与另一个 {}

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

<块引用>

文字字符 {} 可以通过以下方式包含在字符串中在它们前面加上相同的字符.例如,{ 字符用 {{ 转义,} 字符用 }} 转义.

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. :-(

解决方案

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

这篇关于如何在 Rust 中的格式字符串中转义花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆