How to use variables and double quotes both in string?

For js, I could use this syntax to include variable and double quotes both in string literal.

let a = 123;
`${a}""`

but for rust, I checked some documents and found that if I use format! marco, I can put variable in string like this.

let world = "world";
format!("hello, {}", world};

If I use raw string literal, I can put double quotes in it like this.
r#"And then I said: "There is no escape!""#;
but can not have variables.

oh, with format! marco, we could put \ before " to escape it. but if there are many double quotes to include, it'll be cumbersome heavily.

So is there any syntax simliar to that in js to put variables and double quotes both in string conveniently?

format!(r#"hello "{}""#, world)
5 Likes

just want to mention, you CAN actually use string interpolation in rust for format!() family macros, like println!(), eprintln!(), etc.

combined with raw string literals, your example can be written as:

fn main() {
    let world = "lovely world";
    println!(r##"hello "{world}""##);
}

run it in playground to see the output:

2 Likes

A single # should be enough for the raw string literal in this case, as the string literal does not contain any “"#” sequence. The double, triple, etc ###… sequences are only needed rarely. E.g. for something like println!(r##"hello "#{world}#""##);, printing “hello "#lovely world#":slightly_smiling_face:, or if you want to put a rust programs containing raw strings into a raw string, e.g.

const S: &str = r###"fn main() {
    let world = "lovely world";
    println!(r##"hello "#{world}#""##);
}"###;

fn main() {
    println!("{S}");
}

printing

fn main() {
    let world = "lovely world";
    println!(r##"hello "#{world}#""##);
}
4 Likes