我试图让 &str 和 &str 在 for 循环中连接,目的是在添加了许多部分后使用新的组合字符串。for 循环的一般布局如下所示,但由于大量错误,我在组合字符串时遇到了很多麻烦。
for line in reader.lines() {
let split_line = line.unwrap().split(",");
let mut edited_line = "";
for word in split_line {
if !word.contains("substring") {
let test_string = [edited_line, word].join(",");
edited_line = &test_string;
}
}
let _ = writeln!(outfile, "{}", edited_line).expect("Unable to write to file");
}
Run Code Online (Sandbox Code Playgroud)
第一个错误:
error[E0716]: temporary value dropped while borrowed
Run Code Online (Sandbox Code Playgroud)
运行上面的时候来。
第二个错误:
error[E0308]: mismatched types expected &str, found struct std::string::String
Run Code Online (Sandbox Code Playgroud)
当您从 test_string 中删除 & 并将其分配给edited_line 时发生
注意:format!和concat!宏都给出错误 2。 …
标题说明了一切。我需要&alloc::string::String根据我在尝试写入文件时遇到的错误将 from 转换为字符串文字(我认为是 &str )。我如何将我拥有的转换成它?
这里的总体目标是从一个文件中读取并逐行追加到另一个文件中。
完整代码:
use std::{
fs::File,
io::{self, BufRead, BufReader},
fs::OpenOptions,
fs::write,
any::type_name,
path::Path,
io::Write,
};
fn type_of<T>(_: T) -> &'static str {
type_name::<T>()
}
fn main(){
let inpath = Path::new("tool_output.txt");
let outpath = Path::new("test_output.txt");
let indisplay = inpath.display();
let outdisplay = outpath.display();
let mut infile = match File::open(&inpath) {
Err(why) => panic!("couldn't open {}: {}", indisplay, why),
Ok(infile) => infile,
};
let mut outfile = match OpenOptions::new().write(true).append(true).open(&outpath) {
Err(why) => panic!("couldn't open {}: {}", …Run Code Online (Sandbox Code Playgroud) ascii::AsciiString::from_ascii在字节数组上运行时出现错误。
错误是 thread 'main' panicked at 'Failed: the byte at index 3 is not ASCII'
位置 3 处的字节是 137,它应该是 a ë。我还得到了位置 2 和 4 的值,只是为了确定我的索引没有任何问题,而且它们似乎都有合适的值。
bytes[2] = 38 // &
bytes[3] = 137 // ë
bytes[4] = 56 // 8
我不明白我在这里做错了什么。阅读此功能的文档我不完全确定为什么这不起作用。
我做错了什么,为什么会抛出这个错误?