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

Joh*_*867 2 rust

标题说明了一切。我需要&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 {}: {}", 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

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"); 
   |                               ^^^^^^^^^^^
   |
Run Code Online (Sandbox Code Playgroud)

小智 5

字符串文字是它说什么-一个字面所以"literal"是一个字符串。要使用writeln宏来编写字符串,您必须这样做writeln!(outfile, "{}", line),这里"{}"是格式字符串文字。如果您曾经使用过println宏,基本上就是这样,但是您指定要打印到哪个流。