如何写出非文字字符串?

时间:2014-05-05 16:54:03

标签: string io rust

如何写出s的内容?

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

let s = "foo";

file.write(bytes!(s));   // error: non-literal in bytes!

感谢。

2 个答案:

答案 0 :(得分:1)

使用write_str

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

let s = "foo";

file.write_str(s);

答案 1 :(得分:1)

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返回一个字符串切片,即。一个&str。与字符串文字相关联的变量也是字符串切片,但引用具有静态生命周期,即。 &'static str

如果您可以分别轻松地编写文字和字符串,那么您将采取以上措施。如果需要更复杂的东西,这将有效:

    //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());