简体   繁体   中英

What is the most painless way to add a newline to the end of a String (or &str) in Rust?

I have some user input (String) and intend to write it to a file, and am trying to figure out how to separate all writings to said file by newlines.

let my_string = "my user input";
write_to_file(my_string);

I don't think it's best practice to add a separate write for the newline ( file.write_all("\\n".as_bytes()) ) in my write_file() function but after trying to concatenate with the format macro ( format!("{}\\n", my_string) ) and some pathetic attempts at messing with ownership I'm still unable to add newlines in a "proper" way (although maybe there isn't one, due to the way Rust is built).

Edit: I'm not using a BufWriter and just interfacing directly with std::fs

If you are writing to a File or anything else implementing the Write trait, you can simply use the writeln! macro:

use std::io::Write;
fn main() {
    let mut write_vec: Vec<u8> = vec!();

    // using a boxed Write trait object here to show it works for any Struct impl'ing Write
    // you may also use a std::fs::File here
    let mut write: Box<&mut dyn Write> = Box::new(&mut write_vec);
    writeln!(write, "Hello world").unwrap();
    
    assert_eq!(write_vec, b"Hello world\n");
}

Playground link

Mutating strings is inefficient: if you're steaming data to disk, just let the file system handle the “concatenation”. If all you need to do is write a line to a file with a new line at the end, you can just write a function to abstract those two steps into one.

That being said, I'm sure there's probably a better way to do what you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM