Reputation: 103
The title says it all really. I need to convert from &alloc::string::String
to a string literal (&str I think) according to the error I am getting when I am trying to write to a file. How do I convert what I have into that?
The overall goal here is to read from one file and line by line append to another.
Full code:
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:
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");
| ^^^^^^^^^^^
|
Upvotes: 2
Views: 359
Reputation: 76
A string literal is what it says - a literal so "literal"
is a string literal. To use writeln
macro to write a string, you have to do writeln!(outfile, "{}", line)
and here "{}"
is the format string literal. If you’ve ever used println
macro, it’s basically that but you specify what stream to print to.
Upvotes: 5