diff options
author | Jasper Ras <jras@hostnet.nl> | 2025-08-21 22:09:29 +0200 |
---|---|---|
committer | Jasper Ras <jras@hostnet.nl> | 2025-08-21 22:09:29 +0200 |
commit | 27514d58573ce1f844af4ea60afa72c7f58f1cd7 (patch) | |
tree | 4b16c31f73cb72435d03d5e105261143f8ca135f /Lifetime.md | |
parent | 22675cd8dc75d8b8d4b0f818f5b093efbc364802 (diff) |
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 |