我正在编写一个程序来处理由数字和字母组合而成的向量(因此是 Vec<String>
)。我用 .sort()
对它进行排序方法,现在正在尝试将其写入文件。
在哪里strvec
是我尝试使用 std::fs::write
编写的排序向量;
println!("Save results to file?");
let to_save: String = read!();
match to_save.as_str() {
"y" => {
println!("Enter filename");
let filename: String = read!();
let pwd = current_dir().into();
write("/home/user/dl/results", strvec);
Rust 告诉我“特征 AsRef<[u8]>
没有为 Vec<String>
实现”。我也试过使用 &strvec
.
我该如何避免/修复它?
最佳答案
在将对象写入文件时,您可能需要考虑序列化。 Rust 中最常用的库是 serde ,但是在这个例子中,你想要存储字符串向量,如果你不需要文件中任何人类可读的东西(但它有小尺寸:P),你也可以使用 bincode :
use std::fs;
use bincode;
fn main() {
let v = vec![String::from("aaa"), String::from("bbb")];
let encoded_v = bincode::serialize(&v).expect("Could not encode vector");
fs::write("file", encoded_v).expect("Could not write file");
let read_v = fs::read("file").expect("Could not read file");
let decoded_v: Vec<String> = bincode::deserialize(&read_v).expect("Could not decode vector");
println!("{:?}", decoded_v);
}
记得在Cargo.toml的dependencies下添加bincode = "1.3.3"
#编辑: 实际上,您可以轻松地将 String 保存到文件中,所以简单的 join() 应该这样做:
use std::fs;
fn main() {
let v = vec![
String::from("aaa"),
String::from("bbb"),
String::from("ccc")];
fs::write("file", v.join("\n")).expect("");
}
关于rust - 使用 std::fs::write 将 Vec<String> 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72957085/