From 27514d58573ce1f844af4ea60afa72c7f58f1cd7 Mon Sep 17 00:00:00 2001 From: Jasper Ras Date: Thu, 21 Aug 2025 22:09:29 +0200 Subject: vault backup: 2025-08-21 22:09:29 --- Lifetime.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Lifetime.md (limited to 'Lifetime.md') 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 -- cgit v1.2.3