簡體   English   中英

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

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

我有一些用戶輸入(字符串)並打算將其寫入文件,並試圖弄清楚如何通過換行符將所有文字分隔到所述文件中。

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

我認為在我的write_file()函數中為換行符( file.write_all("\\n".as_bytes()) )添加單獨的寫入不是最佳做法,但在嘗試與格式宏( format!("{}\\n", my_string) ) 和一些試圖弄亂所有權的可悲嘗試,我仍然無法以“正確”的方式添加換行符(盡管由於 Rust 的構建方式,可能沒有換行符)。

編輯:我沒有使用 BufWriter,只是直接與 std::fs 接口

如果您正在寫入File或其他任何實現Write特性的內容,您可以簡單地使用writeln! 宏:

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");
}

游樂場鏈接

改變字符串效率低下:如果您將數據傳輸到磁盤,只需讓文件系統處理“連接”即可。 如果您需要做的只是向文件中寫入一行並在末尾添加一個新行,則只需編寫一個函數即可將這兩個步驟抽象為一個步驟。

話雖如此,我相信可能有更好的方法來做你想做的事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM