-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathgeneric_lifetime.rs
More file actions
68 lines (56 loc) · 1.38 KB
/
Copy pathgeneric_lifetime.rs
File metadata and controls
68 lines (56 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#![allow(unused)]
// Every reference has a lifetime
// Both x and y live at least 'a
fn longest_str<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
// Multiple lifetime
fn print_refs<'a, 'b>(x: &'a str, y: &'b str) {
println!("{} {}", x, y);
}
// Must return correct lifetime
fn f_out<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {
// Cannot return y since lifetime of return type is 'a
x
}
// Elision - Rust figures out the lifetime
fn no_need_to_declare_lifetime(x: &str) {
println!("{}", x);
}
// Struct example
#[derive(Debug)]
struct Book<'a> {
title: &'a str,
}
impl<'a> Book<'a> {
fn edit(&mut self, new_title: &'a str) {
self.title = new_title;
}
}
fn main() {
let x = "Hello".to_string();
// This will not compile (z lives longer than y)
/*
let z = {
let y = "Rust".to_string();
longest_str(&x, &y)
};
println!("longest {:?}", z);
*/
// This compiles (z lives atleast as long as both x and y)
let y = "Rust".to_string();
let z = longest_str(&x, &y);
println!("longest {:?}", z);
// Static lifetime
let s: &'static str = "Hello";
// Placeholder lifetime - let Rust infer the lifetime
let s: &'_ str = "Rust";
// Book
let mut book = Book { title: "Rust" };
book.edit("Solidity");
println!("book: {:?}", book);
}