最佳答案
There are several questions that seem to be about the same problem I'm having. For example see here and here. Basically I'm trying to build a String
in a local function, but then return it as a &str
. Slicing isn't working because the lifetime is too short. I can't use str
directly in the function because I need to build it dynamically. However, I'd also prefer not to return a String
since the nature of the object this is going into is static once it's built. Is there a way to have my cake and eat it too?
Here's a minimal non-compiling reproduction:
fn return_str<'a>() -> &'a str {
let mut string = "".to_string();
for i in 0..10 {
string.push_str("ACTG");
}
&string[..]
}