我正在尝试弄清楚如何将字符串写入文件。以下代码给出了错误:格式参数必须是字符串字面值
:
use std::fs::File;
use std::io::{Error, Write};
fn main() -> Result<(), Error> {
let path = "results.txt";
let mut output = File::create(path)?;
let line = println!("{}", "hello");
write!(output, line);
}
如何从字符串变量中将内容写入文件?如果我更改以下行,它可以工作,但是如果字符串在变量中,我就无法想出如何将其写入文件。
我该怎么做呢?
write!(output, "foo,bar,baz");
println!
的返回类型是单元类型(unit); 它会将格式化的字符串打印到标准输出(stdout)---也许考虑使用format!
替代? - kopecsprintln!
返回一个字符串。你觉得let hello = String::from("Hello, world!");
怎么样? - Sheraffwrite!(output, "{}", line);
。 - turtle