简体   繁体   English

在 Rust 中将换行符添加到字符串(或 &str)末尾的最轻松的方法是什么?

[英]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).我认为在我的write_file()函数中为换行符( file.write_all("\\n".as_bytes()) )添加单独的写入不是最佳做法,但在尝试与格式宏( format!("{}\\n", my_string) ) 和一些试图弄乱所有权的可悲尝试,我仍然无法以“正确”的方式添加换行符(尽管由于 Rust 的构建方式,可能没有换行符)。

Edit: I'm not using a BufWriter and just interfacing directly with std::fs编辑:我没有使用 BufWriter,只是直接与 std::fs 接口

If you are writing to a File or anything else implementing the Write trait, you can simply use the writeln!如果您正在写入File或其他任何实现Write特性的内容,您可以简单地使用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.话虽如此,我相信可能有更好的方法来做你想做的事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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