Add String::from_with_capacity(value, capacity)
#54460
Open
Description
In some situations it would be useful to create a string from a &str with a bigger capacity if it is know that the string is extended later on.
fn main() {
let mut s = String::from("Hello world");
println!("len: {}, cap: {}", s.len(), s.capacity());
s.push_str("add more characters");
s.push_str("and more");
s.push_str("and even more");
println!("len: {}, cap: {}", s.len(), s.capacity());
}
len: 11, cap: 11
len: 51, cap: 60
To not have unused capacity, I wonder if we could have something like String::from_with_capacity()
fn main() {
let mut s = String::from_with_capacity("Hello world", 51);
println!("len: {}, cap: {}", s.len(), s.capacity());
s.push_str("add more characters");
s.push_str("and more");
s.push_str("and even more");
println!("len: {}, cap: {}", s.len(), s.capacity());
}
len: 11, cap: 51
len: 51, cap: 51
This would be a shorter way of writing
let mut s = String::with_capacity(51);
s.push_str("Hello world");
....