I have a function which builds String's and collects string slices in some data structure (and they have to be string slices -- I cannot change that data structure).
The code looks roughly as following:
fn func() {
let data = ...;
for x in xyz {
let val = format!("hello {}", x); // creating new string
data.push(val.as_str()); // getting string slice!
}
// ...use data somehow...
// ...it's ok to drop all the strings here -- data will no longer be used
}
Now, this example obviously won't work as string only lives till the end of the 'for' block. I want to extend it's lifecycle to the whole function.
Now, theoretically, having a vector of strings created at the beginning of the function (to collect those strings) would work as string slices are (as far as I understand) should not move during vector resizes.
However, Rust will not allow me to do that as adding string to vector would require mutable borrow of the vector and string slice will use immutable borrow of the same vector (and, of course, it will be right -- certain modifications on this vector, like removal of the element, would invalidate string slice).
Any advices?
So, essentially, I need some "black hole" data structure which I can throw my String into and get reference to the String valid till the end of the data structure itself.
P.S. I guess, I'm wrong about the vector -- string slices will be invalidated on vector resizes. Ok, then it could be linked list instead, with append-only operation.
P.P.S Something like that?
fn func() {
let warehouse = Warehouse::new();
let data = ...;
for x in xyz {
// returns &String with lifetime of Warehouse!
let val: &String = warehouse.store(format!("hello {}", x));
data.push(val.as_str());
}
// ...use data somehow...
// ...warehouse is destroyed with all its contents
}