Question

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.

Was it helpful?

Solution

Use write_str:

let mut file = File::create(&Path::new("foo.txt"));

let s = "foo";

file.write_str(s);

OTHER TIPS

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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top