See the following Rust Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=272b2760cc6a2796cf913ee584fc4205
The above is a contrived example of something I'm running into. I'm trying to implement an external trait for which one of its function signatures takes in a reference and then returns a Future<...> (which necessarily holds a reference to data that can generate the result of the Future, I think).
The playground version is just trying to mutate a string and return a reference to the mutated string, which is a similar situation. In the example, fn mutate_string(...) is a trait function whose signature I can't modify.
My naive attempt at solving the problem is the provided mutate_string_internal() function, which mutates then returns an owned data type. The problem is, I can't then return a reference to the owned String from the parent function, because the String is owned by the internal function and goes out of scope when the function ends.
mutate_string_trivial() has the correct function signature and works, but I can't figure out how to actually mutate the string, because I have no mutable arguments, I'd need to create data owned by the function to cause a mutation, and then I can't return a reference to it because it goes out of scope.
The only way I can think of to solve this off the top of my head would be to essentially implement a manual garbage collector, where I create a lazy_static variable to own the data with a reference counter. I can then return a reference to the data owned by the lazy_static global variable.
Then I'd need to periodically check and if the only reference left is the lazy_static's, it "garbage collects" and deletes the owning variable.
Are there any reasonable patterns to solve this conundrum? Am I misunderstanding something or missing something obvious? Or am I approaching this from the wrong direction somehow?
A browser interface to the Rust compiler to experiment with the language