Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape curly braces in a format string in Rust

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

like image 938
Christoph Avatar asked Aug 29 '14 13:08

Christoph


People also ask

How do you escape curly braces in string format?

To escape curly braces and interpolate a string inside the String. format() method use triple curly braces {{{ }}} . Similarly, you can also use the c# string interpolation feature instead of String.

How do you escape curly braces in HTML?

Use "{{ '{' }}") to escape it.)

How do you escape curly braces in TCL?

The only way to have non-matching braces is to quote/escape them with a backslash, but no backslash substitutions will be performed, so the backslash goes into the string along with the lone brace.

How do you pass curly braces in JSON?

Data is represented in name/value pairs. Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma). Square brackets hold arrays and values are separated by ,(comma).


1 Answers

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

like image 186
nos Avatar answered Sep 21 '22 19:09

nos