0

I have a simple file, in which I want to add some value from rust in the place of {} holders. Is there a way to mimic passing the content variable like if the string is hardcoded there? If not, how can I achieve a basic templating system with built-in rust features?

  • file.txt:
Hello this is from rust: {}
  • Rust code:
use std::fs;
let mut content = fs::read_to_string("file.txt").unwrap().as_mut_str();
format!(content, "SDSD");

Rust is giving me this error:

format argument must be a string literal rustc
main.rs(17, 13): you might be missing a string literal to format with: `"{} {}",
  • Cargo check:
error: format argument must be a string literal
  --> src\main.rs:17:13
   |
17 |     format!(content, "SDSD");
   |             ^^^^^^^
   |
help: you might be missing a string literal to format with
   |
17 |     format!("{} {}", content, "SDSD");
   |             ++++++++

error: could not compile `web_server` due to previous error

Edit:

I know that format requires a string literal, like I asked above, I wanted to know if there is a way that can "mimic" a variable reference as a string literal. The question there asks for the solution to this error (just use format!("{}", contents)), which is not the solution of this question.

plutolaser
  • 448
  • 4
  • 17
  • 2
    Does this answer your question? [println! error: expected a literal / format argument must be a string literal](https://stackoverflow.com/a/27734844/401059). There's crates for this, though, `runtime_fmt`, e.g. – Caesar Sep 25 '22 at 08:02
  • 1
    The format! macro can't work that way. You may prefer to use someting like `Regex::replace` for this kind of pattern. See https://docs.rs/regex/1.6.0/regex/struct.Regex.html#method.replace – Peterrabbit Sep 25 '22 at 08:47
  • 1
    Perhaps this answers your question [How can I use a dynamic format string with the format! macro?](/q/32572486/2189130) – kmdreko Sep 25 '22 at 14:42
  • 1
    Or, if your file is available at compile-time, you can use [`include_str!`](https://doc.rust-lang.org/std/macro.include_str.html) to get it as a string literal. – kmdreko Sep 25 '22 at 14:43

0 Answers0