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: docs/docs/lifetimes/index.html
+2-2Lines changed: 2 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -1,7 +1,7 @@
1
1
<!doctype html><htmllang=en-US><head><metacharset=utf-8><metaname=viewportcontent="width=device-width,initial-scale=1"><metaname=descriptioncontent="Rust Programming Language Tutorials for Everyone!"><metaname=authorcontent="Dumindu Madunuwan"><metaname=theme-colorcontent="#ffffff" media="(prefers-color-scheme: light)"><metaname=theme-colorcontent="#101010" media="(prefers-color-scheme: dark)"><title>Lifetimes · Learning Rust</title>
2
2
<linkrel=canonicalhref=https://learning-rust.github.io/docs/lifetimes/><linkrel=stylesheethref=/assets/css/docs.min.8e9408609771a441499aa5571a4585b0ca95783b842d5c758af5eef1457b0fe0.cssintegrity><linkrel=manifesthref=/manifest.json><linkrel=iconhref=/favicon/favicon.ico><linkrel=iconhref=/favicon/favicon-16x16.pngsizes=16x16type=image/png><linkrel=iconhref=/favicon/favicon-32x32.pngsizes=32x32type=image/png><linkrel=apple-touch-iconhref=/favicon/apple-touch-icon.pngsizes=180x180><scriptasyncsrc="https://www.googletagmanager.com/gtag/js?id=G-FZHQCXSZ89"></script><script>window.dataLayer=window.dataLayer||[];functiongtag(){dataLayer.push(arguments)}gtag("js",newDate),gtag("config","G-FZHQCXSZ89")</script></head><body><divid=outer-wrapper><divid=aside-wrapper><aside><div><buttonclass=btn><i>❌</i>Close</button></div><ahref=https://learning-rust.github.io/class=site-logo>Learning Rust</a><navrole=navigation><detailsopen><summary>Documentation</summary><ul><li><ahref=https://learning-rust.github.io/docs/overview/>Overview</a></li></ul></details><detailsopen><summary>Basics</summary><ul><li><ahref=https://learning-rust.github.io/docs/why-rust/>Why Rust?</a></li><li><ahref=https://learning-rust.github.io/docs/installation/>Installation</a></li><li><ahref=https://learning-rust.github.io/docs/hello-world/>Hello World</a></li><li><ahref=https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/>Cargo, Crates and Basic Project Structure</a></li><li><ahref=https://learning-rust.github.io/docs/comments-and-documenting-the-code/>Comments and Documenting the code</a></li><li><ahref=https://learning-rust.github.io/docs/variable-bindings-constants-and-statics/>Variable bindings, Constants and Statics</a></li><li><ahref=https://learning-rust.github.io/docs/functions/>Functions</a></li><li><ahref=https://learning-rust.github.io/docs/primitive-data-types/>Primitive Data Types</a></li><li><ahref=https://learning-rust.github.io/docs/operators/>Operators</a></li><li><ahref=https://learning-rust.github.io/docs/control-flows/>Control Flows</a></li></ul></details><detailsopen><summary>Beyond The Basics</summary><ul><li><ahref=https://learning-rust.github.io/docs/vectors/>Vectors</a></li><li><ahref=https://learning-rust.github.io/docs/structs/>Structs</a></li><li><ahref=https://learning-rust.github.io/docs/enums/>Enums</a></li><li><ahref=https://learning-rust.github.io/docs/generics/>Generics</a></li><li><ahref=https://learning-rust.github.io/docs/impls-and-traits/>Impls and Traits</a></li></ul></details><detailsopen><summary>The Tough Part</summary><ul><li><ahref=https://learning-rust.github.io/docs/ownership/>Ownership</a></li><li><ahref=https://learning-rust.github.io/docs/borrowing/>Borrowing</a></li><li><aclass=activehref=https://learning-rust.github.io/docs/lifetimes/>Lifetimes</a></li></ul></details><detailsopen><summary>Let's Get It Started</summary><ul><li><ahref=https://learning-rust.github.io/docs/code-organization/>Code Organization</a></li><li><ahref=https://learning-rust.github.io/docs/functions-02/>Functions (02)</a></li><li><ahref=https://learning-rust.github.io/docs/modules/>Modules</a></li><li><ahref=https://learning-rust.github.io/docs/crates/>Crates</a></li><li><ahref=https://learning-rust.github.io/docs/workspaces/>Workspaces</a></li><li><ahref=https://learning-rust.github.io/docs/use/>Use</a></li><li><ahref=https://learning-rust.github.io/docs/std-primitives-and-preludes/>STD, Primitives and Preludes</a></li></ul></details><detailsopen><summary>Error Handling</summary><ul><li><ahref=https://learning-rust.github.io/docs/smart-compiler/>Smart Compiler</a></li><li><ahref=https://learning-rust.github.io/docs/panicking/>Panicking</a></li><li><ahref=https://learning-rust.github.io/docs/option-and-result/>Option and Result</a></li><li><ahref=https://learning-rust.github.io/docs/unwrap-and-expect/>Unwrap and Expect</a></li><li><ahref=https://learning-rust.github.io/docs/error-and-none-propagation/>Error and None Propagation</a></li><li><ahref=https://learning-rust.github.io/docs/combinators/>Combinators</a></li><li><ahref=https://learning-rust.github.io/docs/custom-error-types/>Custom Error Types</a></li></ul></details></nav></aside></div><divid=content-wrapper><header><ahref=https://learning-rust.github.io/class=site-logo>Learning Rust</a></header><main><article><nav><buttonclass=btn><i>⬅️</i> On this section</button>
3
3
<buttonclass=btn>On this page <i>➡️</i></button></nav><header><h1>Lifetimes</h1><p></p></header><divid=article-body><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><p>Think,</p><ul><li>We have a <strong>variable binding</strong>, <code>a</code>.</li><li>We are <strong>referencing</strong> the value of <code>a</code>, <strong>from another variable binding</strong><code>x</code>.
4
-
We have to make sure that <strong><code>a</code> lives until we stop using <code>x</code></strong>.</li></ul><blockquote><p>🔎 <strong>Memory management</strong> is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of programming languages used <strong>Manual Memory Management</strong> which <strong>requires the programmer to give manual instructions</strong> to identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented <strong>Garbage collection</strong>(GC), a form of <strong>Automatic Memory Management</strong>(AMM). It determines what memory is no longer used and frees it automatically instead of relying on the programmer. However <strong>Objective-C and Swift</strong> provide similar functionality through <strong>Automatic Reference Counting</strong>(ARC).</p></blockquote><h2id=what-is-lifetime>What is Lifetime?</h2><p>In Rust,</p><ul><li>A resource can only have <strong>one owner</strong> at a time. When it goes <strong>out of the scope</strong>, Rust removes it from the Memory.</li><li>When we want to reuse the same resource, we are <strong>referencing</strong> it/ <strong>borrowing</strong> its content.</li><li>When dealing with <strong>references</strong>, we have to specify <strong>lifetime annotations</strong> to provide instructions for the <strong>compiler</strong> to set <strong>how long</strong> those referenced resources <strong>should be alive</strong>.</li><li>⭐ But because of lifetime annotations make the <strong>code more verbose</strong>, in order to make <strong>common patterns</strong> more ergonomic, Rust allows lifetimes to be <strong>elided/omitted</strong> in <code>fn</code> definitions. In this case, the compiler assigns lifetime annotations <strong>implicitly</strong>.</li></ul><p>Lifetime annotations are <strong>checked at compile-time</strong>. Compiler checks when a data is used for the first and the last times. According to that, Rust manages memory in <strong>run time</strong>. This is the major reason for <strong>slower compilation times</strong> in Rust.</p><blockquote><ul><li>Unlike C and C++, <strong>usually</strong>, Rust doesn’t explicitly drop values at all.</li><li>Unlike GC, Rust doesn’t place deallocation calls where the data is no longer referenced.</li><li>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.</li></ul></blockquote><h2id=usage>Usage</h2><p>Lifetimes are denoted with an apostrophe. By convention, a lowercase letter is used for naming. Usually <strong>starts with</strong><code>'a</code> and <strong>follows alphabetic order</strong> when we need to add <strong>multiple lifetime</strong> annotations.</p><p>When using references,</p><h3id=01-on-function-declaration>01. On Function Declaration</h3><ul><li><p>Input and output parameters with references should attach lifetimes after the <code>&</code> sign.
4
+
We have to make sure that <strong><code>a</code> lives until we stop using <code>x</code></strong>.</li></ul><blockquote><p>🔎 <strong>Memory management</strong> is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of programming languages used <strong>Manual Memory Management</strong> which <strong>requires the programmer to give manual instructions</strong> to identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented <strong>Garbage collection</strong>(GC), a form of <strong>Automatic Memory Management</strong>(AMM). It determines what memory is no longer used and frees it automatically instead of relying on the programmer. However <strong>Objective-C and Swift</strong> provide similar functionality through <strong>Automatic Reference Counting</strong>(ARC).</p></blockquote><h2id=what-is-lifetime>What is Lifetime?</h2><p>In Rust,</p><ul><li>A resource can only have <strong>one owner</strong> at a time. When it goes <strong>out of the scope</strong>, Rust removes it from the Memory.</li><li>When we want to reuse the same resource, we are <strong>referencing</strong> it/ <strong>borrowing</strong> its content.</li><li>When dealing with <strong>references</strong>, we have to specify <strong>lifetime annotations</strong> to provide instructions for the <strong>compiler</strong> to set <strong>how long</strong> those referenced resources <strong>should be alive</strong>.</li><li>⭐ But because of lifetime annotations make the <strong>code more verbose</strong>, in order to make <strong>common patterns</strong> more ergonomic, Rust allows lifetimes to be <strong>elided/omitted</strong> in <code>fn</code> definitions. In this case, the compiler assigns lifetime annotations <strong>implicitly</strong>.</li></ul><p>Lifetime annotations are <strong>checked at compile-time</strong>. The compiler checks when data is used for the first and the last times.</p><blockquote><ul><li>Unlike C and C++, <strong>usually</strong>, Rust doesn’t require explicitly dropping values at all.</li><li>Unlike GC, Rust doesn’t place deallocation calls where the data is no longer referenced.</li><li>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.</li></ul></blockquote><h2id=usage>Usage</h2><p>Lifetimes are denoted with an apostrophe. By convention, a lowercase letter is used for naming. Usually <strong>starts with</strong><code>'a</code> and <strong>follows alphabetic order</strong> when we need to add <strong>multiple lifetime</strong> annotations.</p><p>When using references,</p><h3id=01-on-function-declaration>01. On Function Declaration</h3><ul><li><p>Input and output parameters with references should attach lifetimes after the <code>&</code> sign.
5
5
ex. <code>..(x: &'a str)</code> , <code>..(x: &'a mut str)</code></p></li><li><p>After the function name, we should mention that the given lifetimes are generic types.
6
6
ex. <code>fn foo<'a>(..)</code> , <code>fn foo<'a, 'b>(..)</code></p></li></ul><divclass=highlight><pretabindex=0class=chroma><codeclass=language-rustdata-lang=rust><spanclass=line><spanclass=cl><spanclass=c1>// No inputs, return a reference
<ahref=https://learning-rust.github.io/docs/code-organization/>Next <i>﹥</i></a></footer></article><aside><div><buttonclass=btn><i>❌</i>Close</button></div><strong>On this page</strong><navid=TableOfContents><ul><li><ahref=#what-is-lifetime>What is Lifetime?</a></li><li><ahref=#usage>Usage</a><ul><li><ahref=#01-on-function-declaration>01. On Function Declaration</a></li><li><ahref=#02-on-struct-or-enum-declaration>02. On Struct or Enum Declaration</a></li><li><ahref=#03-with-impls-and-traits>03. With Impls and Traits</a></li><li><ahref=#04-with-generic-types>04. With Generic Types</a></li></ul></li><li><ahref=#lifetime-elision>Lifetime Elision</a></li><li><ahref=#static-annotations><code>'static</code> Annotations</a></li><li><ahref=#few-more-examples-about-the-usage-of-rust-lifetimes>Few more examples about the usage of Rust lifetimes.</a></li></ul></nav></aside></main><footer><div><i>🧑💻</i>Built by and copyright<ahref=https://github.com/dumindutarget=_blank>Dumindu Madunuwan</a><i>📅</i> 2016-2025<i>🚀</i><ahref=https://github.com/learning-rusttarget=_blank>GitHub</a></div><div><buttonclass=btn><i>☀️</i><i>⁄</i><i>🌑</i></button></div></footer></div></div><divid=body-model-outer></div><scripttype=text/javascriptsrc=/assets/js/docs.min.12ffdc25c0149ef34e761ee54587f2aae17affcb8375298ad2180851930cb142.jsintegrity></script></body></html>
0 commit comments