let mut some_string = String::from("Hello");
let x: u8 = 10;
some_string.push_str(format!(" {}"), x); // Not allowed!
I wanted to push 10 inside the some_string variable. I can't seem to use the format!() macro for some reason. How come with print!() macro it allows this but not the format!() macro?
So do you mean that format!() allocates new string data and stores it somewhere on the heap? Is that why you used the & so that it will return the ptr instead to the push_str() function?
// allocate a new String and write the formatted result into it
let temp_string = format(" {}", x);
// get a `&str` reference to it
let temp_str = temp_string.as_str();
// actually append it
some_string.push_str(temp_str);
// drop it
drop(temp_string);
write!(writer, "format string", args…) returns a Result, in case the writer fails.
However a String writer never fails (at least I think so), so unwrap is fine.
You can pass a file, bufwriter and many other things to it as well. Those can fail.