ProgrammingRust systems developer

Can a structure in Rust contain references to other objects? What are the lifetime constraints for such references, and what happens when trying to return a structure with invalid lifetimes from a function?

Pass interviews with Hintsage AI assistant

Answer

Structures in Rust can store references to other objects by specifying explicit lifetimes in the structure definition. This is required so that the compiler can check that no reference becomes invalid. Here is an example:

struct Book<'a> { title: &'a str, author: &'a str, }

Here, the Book structure contains two references with the same lifetime 'a. When you write a function that returns such a structure, you must ensure that all references within it will be valid regardless of the internal logic of the function:

fn book_factory<'a>(title: &'a str, author: &'a str) -> Book<'a> { Book { title, author } }

If you try to return a structure from a function where the reference fields point to, for instance, local variables of that function, a compilation error will occur because the lifetimes of the references are insufficient for safe access.

Trick Question

Is it possible to create a structure that contains a reference (&str) in one of its fields and a String in another? Why could this be problematic?

A common mistaken answer: "Yes, it is possible, it is safe".

In reality, if &str is derived from String, and the structure outlives this String, the reference will become dangling. For example:

struct Test<'a> { s1: &'a str, s2: String, } fn main() { let s = String::from("hello"); let t = Test { s1: &s, s2: s }; // t.s1 is actually safe only while s2 (s) is alive, but if s2 is dropped first — it will error }

Examples of Real Errors Due to Ignorance of the Topic


Story In one project, they tried to return from a loading function a structure containing a reference to a temporary string created within the same function. The code could not compile, and significant rewriting was required to eliminate the lifetime of the local variable.


Story A developer intended to use a structure with a reference to an array element created in a function, but after the return, this reference became invalid, which the compiler successfully prevented.


Story In a corporate project, developers stored a reference &str to a string from another object that was removed from the collection before the reference itself—when subsequently accessing this reference, a panic occurred.