gpt4 book ai didi

rust - 如何从 &alloc::string::String 转换为字符串文字?

转载 作者:行者123 更新时间:2023-12-03 11:27:45 24 4
gpt4 key购买 nike

标题确实说明了一切。我需要根据尝试写入文件时遇到的错误,将 &alloc::string::String 转换为字符串文字(我认为是 &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 {}: {}", outdisplay, why),
Ok(outfile) => outfile,
};

let reader = BufReader::new(infile);

for line in reader.lines() {
let format_line = String::from(line.unwrap()); // <- I thought this would fix the error but it didnt.
println!("Type = {}", type_of(&format_line));
let _ = writeln!(outfile, &format_line).expect("Unable to write to file"); <- this is currently causing the error.
//write("test_output.txt", line.unwrap()).expect("Unable to write to file");
}
}

错误:

error: format argument must be a string literal
--> text_edit.rs:36:28
|
36 | let _ = writeln!(outfile, format_line).expect("Unable to write to file");
| ^^^^^^^^^^^
|

最佳答案

字符串文字就是它所说的 - 文字,因此 "literal" 是字符串文字。要使用 writeln 宏写入字符串,您必须执行 writeln!(outfile, "{}", line) 和此处的 "{}" 是格式字符串文字。如果您曾经使用过 println 宏,基本上就是这样,但您指定要打印到哪个流。

关于rust - 如何从 &alloc::string::String 转换为字符串文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62764886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com