How to best handle shared pieces of data?

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.

Arc is the correct type for sharing, so Arc<Regex> allows you to share the same regex object and not have the program paralyzed by lifetime limits of scope-bound loans. & is just a temporary permission to view something.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.