[rust-dev] Help understanding lifetimes.

Steven Blenkinsop steven099 at gmail.com
Mon Dec 24 12:14:16 PST 2012


I was trying to see how to use region pointers to return nested data in a
data structure containing unique pointers. This works:

struct T1 { value: int }
struct T2 { t1: ~T1 }

fn value(t2: &r/T2) -> &r/int {
        &t2.t1.value
}

fn main() {
        let t2 = ~T2{ t1: ~T1{ value: 5 } };
        io::println(fmt!("%d", *value(t2)));
}

This makes sense to me, since the data structure as a whole is immutable
for the duration of the borrow, so the lifetime of all nested values should
be the lifetime of the owning reference.

However, if I try to introduce an option type, I can't figure out how to
get it to work.

struct T1 { value: int }
struct T2 { t1: option::Option<~T1> }

If I try to borrow T1.value inside a match in fn value, it tells me it's an
illegal borrow since the borrowed value is only valid inside the match. Is
there a way to get this to work, or is it impossible, and if the latter,
what's the reasoning for this?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20121224/aa2b659b/attachment.html>


More information about the Rust-dev mailing list