Search code examples
rust

Can I use raw string literal with variables?


I know I can use format! to create a String with variables.

let name = "rust";
format!("Hi, {}", name);

However, I am using a raw string literal to make data in Json format (so that I do not need to use an escape character). Is there any way to use a variable in a string while using a raw string literal?


Solution

  • To work with owned strings format! is a great choice and a good solution. You can use it with syntax below:

    let name = "rust";
    format!("Hi {name}");
    

    Additionally, as you mentioned using JSON in your project I would like to recommend serde_json library that provides json!() macro which let you write json-like structure that will be serialize/deserialize as you want.

    let name = "rust";
    let json = json!(
    {
      "foo": name,
      "bar": "kekw"
    }
    )
    

    If do you want more concrete answer, you'll have to provide more information about what you're actually trying to do.