November 2017
Beginner
308 pages
8h 32m
English
As with borrowing, we have to consider the scope to ensure that things work correctly.
The following piece of code, for example, won't work:
struct MyStruct<'a> {
lifea: &'a i32,
}
fn main()
{
let x;
{
let y = &5; // means let y = 5; let y = &y;
let f = MyStruct { lifea: y };
x = &f.lifea
}
println!("{}", x);
}
It may not seem obvious at first why this should not work. In terms of scope, f is created after y, so is in the scope of y and y is created within the scope of x. Or is it?
When the code is built, we will get the following output:
The error will be the x = &f.lifea, as we attempted to ...
Read now
Unlock full access