Hi there.
Say I have a variable headers: Vec<(Variant, Variant)> (where Variant implements ToString) which I want to turn into a Vec<(&str, &str)>. What's the best way to do this? Currently, this is compiling:
Is there a solution where you only need to iterate over the Vec once? I'm getting borrow checker errors complaining that Strings returned by .to_string() do not live long enough that we may be able to return them as &str's. I understand the error, but am not sure how to fix it.
There isn't really much way to fix it, you're probably better off just using Vec<(String, String)> instead. Is there some other context for why that wouldn't work?
In that case, the snippet you gave is probably the best answer. Unless Variant holds a String itself, in which case you can do
let h: Vec<(&str, &str)> = headers.iter()
.map(|(key, val)| {
// where instead of `.my_string()`, whatever function you use to get them
(&*key.my_string(), &*val.my_string())
}).collect();
Otherwise there's no cheap way. ToString doesn't promise that the string exists in memory — it can be dynamically generated on the fly. OTOH &str promises that it already exists in memory.