-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgeneric_lifetime.rs
48 lines (39 loc) · 919 Bytes
/
generic_lifetime.rs
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
#![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
struct Book<'a> {
title: &'a str,
id: u32,
}
impl<'a> Book<'a> {
fn edit(&'a mut self, new_title: &'a str) {
self.title = new_title;
}
}
fn main() {
// Static lifetime
let s: &'static str = "Hello";
// Placeholder lifetime - let Rust infer the lifetime
let s: &'_ str = "Rust";
}