Skip to content

Add String::from_with_capacity(value, capacity) #54460

Open
@matthiaskrgr

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

Metadata

Assignees

No one assigned

    Labels

    A-strArea: str and StringC-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions