[rust-dev] Help understanding lifetimes.

Steven Blenkinsop steven099 at gmail.com
Mon Dec 24 12:29:06 PST 2012


Here's something I tried that seemed the  closest to working, but I don't
know if I'm on the right track at all:
struct T1 { value: int }
struct T2 { t1: option::Option<~T1> }

fn value(t2: &r/T2, def: &r/int) -> &r/int {
        match t2.t1 {
                Some(ref t1) => &t1.value,
                None => def
        }
}

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

Here's the error:

test.rs:6:19: 6:21 error: illegal borrow: borrowed value does not live long
enough
test.rs:6 Some(ref t1) => &t1.value,
                             ^~
test.rs:4:43: 9:1 note: borrowed pointer must be valid for the lifetime &r
as defined on the block at 4:43...
test.rs:4 fn value(t2: &r/T2, def: &r/int) -> &r/int {
test.rs:5 match t2.t1 {
test.rs:6 Some(ref t1) => &t1.value,
test.rs:7 None => def
test.rs:8 }
test.rs:9 }
test.rs:6:18: 6:27 note: ...but borrowed value is only valid for the block
at 6:18
test.rs:6 Some(ref t1) => &t1.value,
                            ^~~~~~~~~



On Mon, Dec 24, 2012 at 3:16 PM, Tim Chevalier <catamorphism at gmail.com>wrote:

> Can you post the code that doesn't work? I have an idea of what might
> be going on, but it's easier for me to explain if I see the code
> you're trying to compile :-)
>
> Cheers,
> Tim
>
> --
> Tim Chevalier * http://catamorphism.org/ * Often in error, never in doubt
> "We know there'd hardly be no one in prison / If rights to food,
> clothes, and shelter were given." -- Boots Riley
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20121224/bc0ceefb/attachment.html>


More information about the Rust-dev mailing list