![](/img/trans.png)
[英]What is the most painless way to add a newline to the end of a String (or &str) in Rust?
[英]What is the most efficient way to prepend a `&str` to a `String`?
將&str
添加到String
的最有效方法是什么? 現在我正在分配一個新的String
並推送給它:
fn push_front(s: String, prefix: &str) -> String {
let prefix = prefix.to_owned();
prefix.push_str(&s);
prefix
}
有沒有更有效的方法? 我在標准庫中沒有看到String::push_front
function 。
您可以使用String::insert_str
:
s.insert_str(0, prefix);
insert_str
不是分配一個新的String
和(可能)為 push 分配,而是在底層向量中保留容量並將s
的元素向右移動。 如果String
已經有足夠的prefix
容量,它會完全避免分配。 這意味着它最多只需要一次分配,而不是兩次。
fn push_front(s: String, prefix: &str) -> String {
s.insert_str(0, prefix);
s
}
這將使用 0-1 分配而不是原始的 1-2。
沒有 String::push_front,但有 String::insert_str。
fn main(){
let a = "foo";
let mut b = "bar".to_owned();
b.insert_str(0,a);
dbg!{b};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.