study_rust_example/generic_traits_lifetime/lifetime_study.rs
1fn outside_scope() {
2 let r;
3 //{
4 let x = 5;
5 // error[E0597]: `x` does not live long enough
6 // 解法将x的生命周期拓展到一样的函数体
7 r = &x;
8 //}
9 println!("r {}", r);
10}
11
12/*
13error[E0106]: missing lifetime specifier
14 --> src/generic_traits_lifetime/lifetime_study.rs:12:38
15 |
1612 | fn longer(str1: &str, str2: &str) -> &str {
17 | ---- ---- ^ expected named lifetime parameter
18 = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `str1` or `str2`
19help: consider introducing a named lifetime parameter
20 |
2112 | fn longer<'a>(str1: &'a str, str2: &'a str) -> &'a str {
22 | ++++ ++ ++ ++
23*/
24// fn longer(str1: &str, str2: &str) -> &str {
25fn longer<'a>(str1: &'a str, str2: &'a str) -> &'a str {
26 if str1.len() >= str2.len() {
27 str1
28 } else {
29 str2
30 }
31}
32
33struct Score<'a> {
34 name: &'a str,
35 score: &'a i32,
36}
37
38impl<'a> Score<'a> {
39 // [规则3]:因为参数之一是 &self ,所以返回类型获取 &self 的生命周期
40 fn get_score(&self) -> &i32 {
41 self.score
42 }
43}
44
45// 能编译过的原因是1.0版本以后,引入了生命周期省略原则,对一些通用确定的情况可以省略繁琐的定义
46fn first_world(str: &str) -> &str {
47 for (index, &item) in str.as_bytes().iter().enumerate() {
48 if item == b' ' {
49 return &str[..index];
50 }
51 }
52 return &str;
53}
54/*
55 [rule1] 转换为:fn first_world<'a>(str: &'a str) -> &str {
56 [rule2] 转换为:fn first_world<'a>(str: &'a str) -> &'a str {
57*/
58
59pub fn lifetime_kown_study<'a>() {
60 outside_scope();
61 let num1: &i32;
62 let num2: &'a i32;
63 let num3: &'a mut i32;
64 let str_result: &str;
65 let str1 = String::from("hello rust lifetime.");
66 {
67 let str2 = String::from("world.");
68 str_result = longer(&str1, &str2);
69 println!("str longer: {}", str_result);
70 }
71 // error[E0597]: `str2` does not live long enough
72 // println!("str_result: {}", str_result);
73
74 let s: &'static str = "test 'static";
75}