Suppose I'm trying to do a fancy zero-copy parser in Rust using &str
, but sometimes I need to modify the text (e.g. to implement variable substitution). I really want to do something like this:
fn main() {
let mut v: Vec<&str> = "Hello there $world!".split_whitespace().collect();
for t in v.iter_mut() {
if (t.contains("$world")) {
*t = &t.replace("$world", "Earth");
}
}
println!("{:?}", &v);
}
But of course the String
returned by t.replace()
doesn't live long enough. Is there a nice way around this? Perhaps there is a type which means "ideally a &str
but if necessary a String
"? Or maybe there is a way to use lifetime annotations to tell the compiler that the returned String
should be kept alive until the end of main()
(or have the same lifetime as v
)?