fnmain() {
let r;
{
let x = 5;
r = &x;
}
println!("r: {}", r);
}
编译产生如下错误:
error[E0597]: `x` does not live long enough
--> src/main.rs:76:18
|
76 | r = &x;
| ^ borrowed value does not live long enough
77 | }
| - `x` dropped here while still borrowed
...
80 | }
| - borrowed value needs to live until here
fnmain() {
let a = 10;
let m;
{
let b = 100;
m = max_num(&a, &b);
assert_eq!(100, *m);
}
println!("max num is {}", m);
}
fnmax_num(a: &i32, b: &i32) -> &i32 {
if *a > *b {
return *a;
}
*b
}
在Rust中,上面的代码会产生编译错误:
error[E0106]: missing lifetime specifier
--> src/main.rs:23:33
|
23 | fnmax_num(a: &i32, b: &i32) -> &i32 {
| ^ expected lifetime parameter
|
= help: this function'sreturntypecontains a borrowed value, but the signature does
not say whether it is borrowed from `a` or `b`
// 增加生命周期注解fnmax_num<'a>(a: &'ai32, b: &'ai32) -> &'ai32 {
if *a > *b {
return a;
}
b
}
通过增加生命周期注解,编译器就能够判断引用的有效性:
error[E0597]: `b` does not live long enough
--> src/main.rs:16:26
|
16 | m = max_num(&a, &b);
| ^ borrowed value does not live long enough
17 | assert_eq!(100, *m);
18 | }
| - `b` dropped here while still borrowed
19 | println!("max num is {}", m);
20 | }
| - borrowed value needs to live until here
fnmain() {
// let inner = Inner{data:"inner data."};let a = 1000;
let b = 100; //将b的生命周期延长至与a,m相同let m;
{
m = max_num(&a, &b);
assert_eq!(100, *m);
}
println!("max num is {}", m);
}
【3】生命周期注解语法
生命周期注解并不改变任何引用的生命周期的长短。注解语法如下示例:
&i32// a reference
&'ai32// a reference with an explicit lifetime
&'amuti32// a mutable reference with an explicit lifetime