I have code like this:
use std::fmt::Write;
fn main() {
let mut side_str = String::new();
write!(&mut side_str, "world").unwrap();
println!(
"hello_{:?}_",
format!("{:?}", side_str),
);
}
I am getting quotes in the output. How do I write it in a concise manner to not have the quotes?
The placeholder {:?}
uses the Debug
trait to format values. For String
s the debug implementation includes quotes and escape characters. Your code formats the string twice using the Debug
trait, so you get two sets of quotation marks.
world -> "world" -> "\"world\""
If you do not want any quotes, use {}
to format once using the Display
trait. If you want a single set of quotes, use {:?}
once.
println!("hello_{}_", side_str); // hello_world_
println!("hello_{:?}_", side_str); // hello_"world"_