Home > Enterprise >  Return part of a string from a function without additional allocation
Return part of a string from a function without additional allocation

Time:10-08

I would like a function that returns part of a larger string that is internally generated without causing a separate allocation for the returned part:

fn generate_full_string() -> String {"example: 123".to_owned()}
fn generate_partial_string() -> String {
    generate_string()[9..].to_owned()
}

Here, generate_partial_string has the behavior desired: it generates a String using some algorithm (modeled here by generate_full_string) and then returns part of it, specifically, the portion from the 9th character onwards. The problem here, from my understanding, is that when to_owned() is called on the str returned from generate_string()[9..], a new heap allocation is created to store the returned partial string data, and the partial string data from generate_string()[9..] is copied into it.

Instead, I would like to reuse the allocation created in generate_full_string, and use it to store the returned partial string. In other words, I want the String value returned from generate_partial_string to point to the desired portion of the heap allocation created by generate_full_string to hold the full string.

Is it possible to do this in safe Rust? Is there some other API pattern I can use to return a part of a larger string from a function without requiring that function to take ownership of a String from its caller's scope?

CodePudding user response:

You can use .replace_range() with an empty string to remove the prefix:

fn generate_partial_string() -> String {
    let mut full = generate_full_string();
    full.replace_range(..9, "");
    full
}
  • Related