Storing string in a mutable struct with same lifetime

⚓ Rust    📅 2026-01-08    👤 surdeus    👁️ 4      

surdeus

Hi all,

I'm currently working on a parser, and have gotten a bit stuck on reading in other files. In particular, I want a function to read in a file, operate on the contents, and return something with &str references into the file. Since the file names aren't known ahead of time (meaning it can't be read outside the function), my thinking is to store the contents of the file in an external struct, so that the data can be kept alive longer than the function lifetime; something like this:

pub struct MyStruct<'a> {
    // ...
}

fn my_function<'a>(
    storage: &mut MyStruct<'a>
) -> &'a str {
    let contents: String = read_file();
    let content_ref: &'a str = storage.retain(contents);
    content_ref // References the data from `contents`, stored in `storage`
}

At a high-level, I think something like this should be possible; with the 'a lifetime on MyStruct, it should be able to keep data around for at least that long, and provide a reference to it for that lifetime. However, I haven't been able to figure out how to implement this in practice. Using Vec<String> (or elsa::FrozenVec<Box<String>>, which I thought might work) seem to require &'a mut MyStruct<'a>, which isn't doable since I need the mutable reference elsewhere as well. Not sure if this is doable outside of something like Box::leak?

(Still consider myself a Rust newbie, so pardon any obvious errors :slight_smile:)

1 post - 1 participant

Read full topic

🏷️ Rust_feed