Struggling with Lifetime issue


Can somebody explain how to fix up this lifetime issue? I have been using the clang-rs crate to parse some files into AST. Recently I wanted to modify the parse tree structure to retain the clang-rs structs, along with one or more parse trees, so they can be later queried in arbitrary ways. As a result I wanted to write the following struct and impl, which I tried various variations on (e.g without the Option its similar),

pub struct ParserContext<'t> {
clang: Rc,
index: Option<Index<'t>>,

impl<'t> ParserContext<'t> {
pub fn new() -> ParserContext<'t> {
let mut context = ParserContext {
clang: Rc::new(Clang::new().unwrap()),
index: None,
context.index = Some(Index::new(&context.clang, false, false));
return context;

This and many variations produce the compilation error however,

error[E0597]: context.clang does not live long enough --> src\
49 | context.index = Some(Index::new(&context.clang, false, false));
| ^^^^^^^^^^^^^ borrowed value does not live long enough
50 | return context;
51 | }
| - borrowed value only lives until here

Can anybody explain how I can create a context structure containing the Clang and Index structs initialized via this Index::new call which accepts a borrow?

Presently I am a bit confused about why this should be a compile error as the address of the Clang doesn’t change once its placed into its Rc (I believe) so the borrow of the Clang is still valid, I believe.

For context I am a C/C++ programmer who took up rust a couple of months ago.


It could change if something assigned a different value to context.clang altogether! The compiler would need some whole-program analysis to know that doesn’t happen, but rustc only analyzes locally.

Self-referential structs are not well supported in Rust, but you can do it to some extent with rental.