1

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_full_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?

2
  • If you only want to cut off end of a String you can use truncate. Otherwise I think it's impossible. Commented Oct 7, 2022 at 17:45
  • good2know. But, in this case I wish to cut off the beginning of the string. Commented Oct 7, 2022 at 17:53

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.