What is the best approach for handling pieces of data that are frequently added to and removed from a data structure?
For example, this works well (Regex
is just an example here. It could also be String
etc.):
pub struct TokenStream {
pub token_regexes: Vec<&Regex<'static>>,
}
However, what if some regexes have lifetimes that are shorter than 'static
? One option is to give TokenStream
a lifetime annotation. But that makes is much harder (if not impossible) to use.
pub struct TokenStream<'a> {
pub token_regexes: Vec<&Regex<'a>>,
}
Interestingly, usage is often scoped but (AFAIK) there is no way to track the lifetime of a value after it was added to a collection:
token_stream.push(&my_regex);
some_function(&token_stream);
token_stream.pop();
Another option is to always clone Regexes so that TokenStream
owns them. But that seems wasteful.
pub struct TokenStream {
pub token_regexes: Vec<Regex>,
}
Alas, moving is not an option in this case because the same regex has to be added and removed multiple times.