【发布时间】:2014-05-05 16:54:02
【问题描述】:
如何写出s的内容?
let file = File::create(&Path::new("foo.txt"));
let s = "foo";
file.write(bytes!(s)); // error: non-literal in bytes!
谢谢。
【问题讨论】:
如何写出s的内容?
let file = File::create(&Path::new("foo.txt"));
let s = "foo";
file.write(bytes!(s)); // error: non-literal in bytes!
谢谢。
【问题讨论】:
使用write_str:
let mut file = File::create(&Path::new("foo.txt"));
let s = "foo";
file.write_str(s);
【讨论】:
write(bytes!(concat!(s, "bar"))); 连接字符串和非文字字符串 - 但编译器需要文字。有什么线索吗?谢谢。
concat! 的存在。你可能很长一段时间都不需要它。连接字符串通过std::str 或std::strbuf 发生,可能s.append("bar") 用于一次性连接。
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());
【讨论】: