rust - return struct that contains reference

Viewed 60
fn main() {
    let b = foo();
    println!("{}", b.getProp());
}

struct A {
    prop: isize
}

struct B<'a> {
    a: &'a A
}

impl<'a> B<'a> {
    fn getProp(&self) -> isize {
        return self.a.prop;
    }
}
fn foo<'a>() -> B<'a> {
    return B {
        a: &(A {
            prop: 3
        })
    };
}

This works,

fn foo<'a>() -> B<'a> {
    let a = A {
        prop: 3
    };
    return B {
        a: &(a)
    };
}

but this one doesn't work.

I already know that it is not able to return reference, but why there is a difference in these two codes?

0 Answers
Related