You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/en/docs/c3.lifetimes.md
+36-24Lines changed: 36 additions & 24 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,41 +3,53 @@ title: Lifetimes
3
3
slug: lifetimes
4
4
---
5
5
6
-
> [!caution]
7
-
> This needs a refresh!
6
+
> [!recap]
7
+
> - Ownership: Each piece of data has a single owner, and data is only scoped to its owner (unless it is borrowed).
8
+
> - In Rust, borrowing is the act of creating a reference to a value without copying the data and without taking ownership (move). While a reference exists, the original owner retains ownership, but its access to the data is restricted (or completely locked if `&mut`) until that reference’s last use.
9
+
> - Liveness:
10
+
> - Owned values (`T`) are dropped at the end of their scope (unless moved early).
11
+
> - References (`&T`, `&mut T`) effectively end/ expire at their last use. This is known as Non-Lexical Lifetimes (NLL).
12
+
> - Lifetimes are Rust's way of guaranteeing that a reference is valid within a discrete region of code at compile time.
8
13
9
-
When we are dealing with references, we have to make sure that the referencing data stay alive until we stop using the references.
14
+
## Lifetimes
10
15
11
-
Think,
16
+
- A lifetime is a construct the Rust compiler's borrow checker uses to track how long references remain valid and every reference in Rust has a lifetime.
17
+
- However, most local lifetimes are implicitly figured out by the compiler through a mechanism called lifetime elision.
18
+
- The primary purpose of lifetimes is to prevent dangling references, ensuring data is never dropped while a pointer still looks at it.
12
19
13
-
- We have a variable binding, `a`.
14
-
- We are referencing the value of `a`, from another variable binding `x`.
15
-
16
-
We have to make sure that `a` lives until we stop using `x`.
20
+
Annotating a lifetime does not extend the lifespan of an actual value. It is simply a contract that tells the compiler, "The lifespan of this reference is guaranteed to be tied to the lifespan of this data."
17
21
18
-
> [!recap]
19
-
> **Memory management** is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of
20
-
> programming languages used Manual Memory Management which requires the programmer to give manual instructions to
21
-
> identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented Garbage collection\(GC\),
22
-
> a form of Automatic Memory Management\(AMM\). It determines what memory is no longer used and frees it automatically instead
23
-
> of relying on the programmer. However, Objective-C and Swift provide similar functionality through Automatic Reference Counting\(ARC\).
22
+
Lifetimes are declared with a single leading apostrophe `'`. By convention, lowercase letters are used starting from `'a`, moving alphabetically if multiple lifetimes are required.
24
23
24
+
```rust
25
+
fnmain() {
26
+
leta="A";
25
27
26
-
## What is Lifetime?
28
+
take_str(a);
29
+
take_str_elided(a);
30
+
}
27
31
28
-
In Rust,
32
+
fntake_str<'a>(x:&'astr) {
33
+
println!("{x}");
34
+
}
29
35
30
-
* A resource can only have **one owner** at a time. When it goes **out of the scope**, Rust removes it from the Memory.
31
-
* When we want to reuse the same resource, we are **referencing** it/ **borrowing** its content.
32
-
* When dealing with **references**, we have to specify **lifetime annotations** to provide instructions for the **compiler** to set **how long** those referenced resources **should be alive**.
33
-
* ⭐ But because of lifetime annotations make the **code more verbose**, in order to make **common patterns** more ergonomic, Rust allows lifetimes to be **elided/omitted** in `fn` definitions. In this case, the compiler assigns lifetime annotations **implicitly**.
36
+
fntake_str_elided(x:&str) {
37
+
println!("{x}");
38
+
}
39
+
```
34
40
35
-
Lifetime annotations are **checked at compile-time**. The compiler checks when data is used for the first and the last times.
41
+
`'static` is a special lifetime that indicating the reference can live for the entire duration of the program execution.
36
42
37
-
> * Unlike C and C++, **usually**, Rust doesn’t require explicitly dropping values at all.
38
-
> * Unlike GC, Rust doesn’t place deallocation calls where the data is no longer referenced.
39
-
> * Rust places deallocation calls where the data is about to go out of the scope and then enforces that no references to that resource exist after that point.
<p>This can be any form of <code>self</code>, <code>&amp;self</code>, <code>&amp;mut self</code>, <code>self: Box&lt;Self&gt;</code>, <code>self: Pin&lt;&amp;mut Self&gt;</code>, etc.</p></description></item><item><title>Installation</title><link>https://learning-rust.github.io/docs/installation/</link><pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate><guid>https://learning-rust.github.io/docs/installation/</guid><description><h2 id="rustup">Rustup</h2>
469
469
<p>There are many ways to install Rust on your system. For the moment the official way to install Rust is using <a href="https://rustup.rs/" target="_blank" >Rustup</a>.</p>
470
470
<p><a href="https://rust-lang.github.io/rustup/index.html" target="_blank" >📖</a> Rustup installs The Rust Programming Language from the official release channels, enabling you to easily switch between <strong>stable, beta, and nightly</strong> compilers and keep them updated. It also makes cross-compiling simpler with binary builds of the standard library for common platforms.</p>
471
-
<p><a href="https://rust-lang.github.io/rustup/installation/index.html" target="_blank" >📖</a> Rustup installs <code>rustc</code>, <code>cargo</code>, <code>rustup</code> and other standard tools to <strong>Cargo&rsquo;s <code>bin</code> directory</strong>. On Unix it is located at <code>$HOME/.cargo/bin</code> and on Windows at <code>%USERPROFILE%\.cargo\bin</code>. This is the same directory that <code>cargo install</code> will install Rust programs and Cargo plugins.</p></description></item><item><title>Lifetimes</title><link>https://learning-rust.github.io/docs/lifetimes/</link><pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate><guid>https://learning-rust.github.io/docs/lifetimes/</guid><description><div class="alert alert-caution">
471
+
<p><a href="https://rust-lang.github.io/rustup/installation/index.html" target="_blank" >📖</a> Rustup installs <code>rustc</code>, <code>cargo</code>, <code>rustup</code> and other standard tools to <strong>Cargo&rsquo;s <code>bin</code> directory</strong>. On Unix it is located at <code>$HOME/.cargo/bin</code> and on Windows at <code>%USERPROFILE%\.cargo\bin</code>. This is the same directory that <code>cargo install</code> will install Rust programs and Cargo plugins.</p></description></item><item><title>Lifetimes</title><link>https://learning-rust.github.io/docs/lifetimes/</link><pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate><guid>https://learning-rust.github.io/docs/lifetimes/</guid><description><div class="alert alert-recap">
<li>Ownership: Each piece of data has a single owner, and data is only scoped to its owner (unless it is borrowed).</li>
488
+
<li>In Rust, borrowing is the act of creating a reference to a value without copying the data and without taking ownership (move). While a reference exists, the original owner retains ownership, but its access to the data is restricted (or completely locked if <code>&amp;mut</code>) until that reference’s last use.</li>
489
+
<li>Liveness:
490
+
<ul>
491
+
<li>Owned values (<code>T</code>) are dropped at the end of their scope (unless moved early).</li>
492
+
<li>References (<code>&amp;T</code>, <code>&amp;mut T</code>) effectively end/ expire at their last use. This is known as Non-Lexical Lifetimes (NLL).</li>
493
+
</ul>
494
+
</li>
495
+
<li>Lifetimes are Rust&rsquo;s way of guaranteeing that a reference is valid within a discrete region of code at compile time.</li>
496
+
</ul>
487
497
</div>
488
-
</div><p>When we are dealing with references, we have to make sure that the referencing data stay alive until we stop using the references.</p>
<li>We have a variable binding, <code>a</code>.</li>
492
-
<li>We are referencing the value of <code>a</code>, from another variable binding <code>x</code>.</li>
500
+
<li>A lifetime is a construct the Rust compiler&rsquo;s borrow checker uses to track how long references remain valid and every reference in Rust has a lifetime.</li>
501
+
<li>However, most local lifetimes are implicitly figured out by the compiler through a mechanism called lifetime elision.</li>
502
+
<li>The primary purpose of lifetimes is to prevent dangling references, ensuring data is never dropped while a pointer still looks at it.</li>
493
503
</ul>
494
-
<p>We have to make sure that <code>a</code> lives until we stop using <code>x</code>.</p></description></item><item><title>Modules</title><link>https://learning-rust.github.io/docs/modules/</link><pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate><guid>https://learning-rust.github.io/docs/modules/</guid><description><div class="alert alert-caution">
504
+
<p>Annotating a lifetime does not extend the lifespan of an actual value. It is simply a contract that tells the compiler, &ldquo;The lifespan of this reference is guaranteed to be tied to the lifespan of this data.&rdquo;</p></description></item><item><title>Modules</title><link>https://learning-rust.github.io/docs/modules/</link><pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate><guid>https://learning-rust.github.io/docs/modules/</guid><description><div class="alert alert-caution">
0 commit comments