diff options
Diffstat (limited to 'Lifetime.md')
-rw-r--r-- | Lifetime.md | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/Lifetime.md b/Lifetime.md new file mode 100644 index 0000000..45ab96c --- /dev/null +++ b/Lifetime.md @@ -0,0 +1,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
\ No newline at end of file |