summaryrefslogtreecommitdiff
path: root/Lifetime.md
blob: 45ab96c7a1b8f8c317e12007ed13230993989eaa (plain)
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
[[Rust]]
[[Data must outlive any references to it]]

Associated permission: Flow:
Indicates whether or not a reference argument is allowed to be used, or a reference is allowed to be returned.

Simple example:
```rust
fn a_or_b(a: &str, b: &str) -> &str {
	if something {
		a
	} else {
		b
	}
}

let a = vec![];
let b = String::from("a");
let c = a_or_b(&a, &b);
drop(b);
println!("{}", c);
```

In the above example `c` is being printed after `b` is dropped but `a_or_b` could have returned `b` so the println uses freed data ( null pointer exception) .

It is also not possible to return a reference to heap data that will be dropped at the end of the function.

```rust
fn epic_ref() -> &str {
	let cool = String::from("yo");
	let coolref = &cool;
	coolref
}
```
^ will fail