Reputation: 1535
How can I write out the contents of s
?
let file = File::create(&Path::new("foo.txt"));
let s = "foo";
file.write(bytes!(s)); // error: non-literal in bytes!
Thanks.
Upvotes: 2
Views: 788
Reputation: 16640
use std::io::File;
fn main() {
let mut file = File::create(&Path::new("foo.txt"));
let literal = "foo";
let string = "bar".to_owned();
file.write_str(literal);
file.write_str(string.as_slice());
}
as_slice
returns a string slice, ie. a &str
. The variables associated with string literals are also a string slice, but the reference has static lifetime, ie. &'static str
.
The above is what you would do if you can comfortably write literals and strings separately. If something more complex is needed, this will work:
//Let's pretend we got a and b from user input
let a = "Bob".to_owned();
let b = "Sue".to_owned();
let complex = format!("{0}, this is {1}. {1}, this is {0}.", a, b);
file.write_str(complex.as_slice());
Upvotes: 1