<!DOCTYPE HTML> <html lang="en" class="sidebar-visible no-js"> <head> <!-- Book generated using mdBook --> <meta charset="UTF-8"> <title>Lifetimes - The Rust Programming Language</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="theme-color" content="#ffffff" /> <base href=""> <link rel="stylesheet" href="book.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css"> <link rel="shortcut icon" href="favicon.png"> <!-- Font Awesome --> <link rel="stylesheet" href="_FontAwesome/css/font-awesome.css"> <link rel="stylesheet" href="highlight.css"> <link rel="stylesheet" href="tomorrow-night.css"> <link rel="stylesheet" href="ayu-highlight.css"> <!-- Custom theme stylesheets --> <link rel="stylesheet" href="src/theme/first-edition.css"> </head> <body class="light"> <!-- Work around some values being stored in localStorage wrapped in quotes --> <script type="text/javascript"> try { var theme = localStorage.getItem('mdbook-theme'); var sidebar = localStorage.getItem('mdbook-sidebar'); if (theme.startsWith('"') && theme.endsWith('"')) { localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1)); } if (sidebar.startsWith('"') && sidebar.endsWith('"')) { localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1)); } } catch (e) { } </script> <!-- Set the theme before any content is loaded, prevents flash --> <script type="text/javascript"> var theme; try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } if (theme === null || theme === undefined) { theme = 'light'; } document.body.className = theme; document.querySelector('html').className = theme + ' js'; </script> <!-- Hide / unhide sidebar before it is displayed --> <script type="text/javascript"> var html = document.querySelector('html'); var sidebar = 'hidden'; if (document.body.clientWidth >= 1080) { try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { } sidebar = sidebar || 'visible'; } html.classList.remove('sidebar-visible'); html.classList.add("sidebar-" + sidebar); </script> <nav id="sidebar" class="sidebar" aria-label="Table of contents"> <ol class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html"><strong aria-hidden="true">1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong aria-hidden="true">2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong aria-hidden="true">3.</strong> Syntax and Semantics</a></li><li><ol class="section"><li><a href="variable-bindings.html"><strong aria-hidden="true">3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong aria-hidden="true">3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong aria-hidden="true">3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong aria-hidden="true">3.4.</strong> Comments</a></li><li><a href="if.html"><strong aria-hidden="true">3.5.</strong> if</a></li><li><a href="loops.html"><strong aria-hidden="true">3.6.</strong> Loops</a></li><li><a href="vectors.html"><strong aria-hidden="true">3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong aria-hidden="true">3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong aria-hidden="true">3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html" class="active"><strong aria-hidden="true">3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong aria-hidden="true">3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong aria-hidden="true">3.12.</strong> Structs</a></li><li><a href="enums.html"><strong aria-hidden="true">3.13.</strong> Enums</a></li><li><a href="match.html"><strong aria-hidden="true">3.14.</strong> Match</a></li><li><a href="patterns.html"><strong aria-hidden="true">3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong aria-hidden="true">3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong aria-hidden="true">3.17.</strong> Strings</a></li><li><a href="generics.html"><strong aria-hidden="true">3.18.</strong> Generics</a></li><li><a href="traits.html"><strong aria-hidden="true">3.19.</strong> Traits</a></li><li><a href="drop.html"><strong aria-hidden="true">3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong aria-hidden="true">3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong aria-hidden="true">3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong aria-hidden="true">3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong aria-hidden="true">3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong aria-hidden="true">3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong aria-hidden="true">3.26.</strong> const and static</a></li><li><a href="attributes.html"><strong aria-hidden="true">3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong aria-hidden="true">3.28.</strong> type aliases</a></li><li><a href="casting-between-types.html"><strong aria-hidden="true">3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong aria-hidden="true">3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong aria-hidden="true">3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong aria-hidden="true">3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong aria-hidden="true">3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong aria-hidden="true">3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong aria-hidden="true">3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong aria-hidden="true">3.36.</strong> unsafe</a></li></ol></li><li><a href="effective-rust.html"><strong aria-hidden="true">4.</strong> Effective Rust</a></li><li><ol class="section"><li><a href="the-stack-and-the-heap.html"><strong aria-hidden="true">4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong aria-hidden="true">4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong aria-hidden="true">4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html"><strong aria-hidden="true">4.4.</strong> Documentation</a></li><li><a href="iterators.html"><strong aria-hidden="true">4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong aria-hidden="true">4.6.</strong> Concurrency</a></li><li><a href="error-handling.html"><strong aria-hidden="true">4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong aria-hidden="true">4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong aria-hidden="true">4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong aria-hidden="true">4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong aria-hidden="true">4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong aria-hidden="true">4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong aria-hidden="true">4.13.</strong> Procedural Macros (and custom derive)</a></li></ol></li><li><a href="glossary.html"><strong aria-hidden="true">5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong aria-hidden="true">6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong aria-hidden="true">7.</strong> Bibliography</a></li></ol> </nav> <div id="page-wrapper" class="page-wrapper"> <div class="page"> <div id="draft-warning" class="warning"> <span class="message">You are reading an <strong>outdated</strong> edition of TRPL. For more, go <a href="../index.html">here</a>.</span> <button type="button" id="hide-draft-warning" title="Hide draft warning" class="button"> <i class="fa fa-times"></i> </button> </div> <!-- Hide / unhide warning before it is displayed --> <script type="text/javascript"> var warning = localStorage.getItem('trpl-first-edition-draft-warning'); if (warning === 'hidden') { Array .from(document.querySelectorAll('#page-wrapper')) .forEach(function(block) { block.classList.remove('has-warning'); }); var elem = document.getElementById("draft-warning"); elem.parentNode.removeChild(elem); } document.addEventListener("DOMContentLoaded", function(event) { document.getElementById("hide-draft-warning").addEventListener("click", function(e) { var elem = document.getElementById("draft-warning"); elem.parentNode.removeChild(elem); localStorage.setItem('trpl-first-edition-draft-warning', 'hidden'); }); }); </script> <div id="menu-bar" class="menu-bar"> <div id="menu-bar-sticky-container"> <div class="left-buttons"> <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar"> <i class="fa fa-bars"></i> </button> <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list"> <i class="fa fa-paint-brush"></i> </button> <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu"> <li role="none"><button role="menuitem" class="theme" id="light">Light <span class="default">(default)</span></button></li> <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li> <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li> <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li> <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li> </ul> <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar"> <i class="fa fa-search"></i> </button> </div> <h1 class="menu-title">The Rust Programming Language</h1> <div class="right-buttons"> <a href="print.html" title="Print this book" aria-label="Print this book"> <i id="print-button" class="fa fa-print"></i> </a> </div> </div> </div> <div id="search-wrapper" class="hidden"> <form id="searchbar-outer" class="searchbar-outer"> <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header"> </form> <div id="searchresults-outer" class="searchresults-outer hidden"> <div id="searchresults-header" class="searchresults-header"></div> <ul id="searchresults"> </ul> </div> </div> <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM --> <script type="text/javascript"> document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible'); document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible'); Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) { link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1); }); </script> <div id="content" class="content"> <main> <a class="header" href="lifetimes.html#lifetimes" id="lifetimes"><h1>Lifetimes</h1></a> <p>This is the last of three sections presenting Rust’s ownership system. This is one of Rust’s most distinct and compelling features, with which Rust developers should become quite acquainted. Ownership is how Rust achieves its largest goal, memory safety. There are a few distinct concepts, each with its own chapter:</p> <ul> <li><a href="ownership.html">ownership</a>, the key concept</li> <li><a href="references-and-borrowing.html">borrowing</a>, and their associated feature ‘references’</li> <li>lifetimes, which you’re reading now</li> </ul> <p>These three chapters are related, and in order. You’ll need all three to fully understand the ownership system.</p> <a class="header" href="lifetimes.html#meta" id="meta"><h1>Meta</h1></a> <p>Before we get to the details, two important notes about the ownership system.</p> <p>Rust has a focus on safety and speed. It accomplishes these goals through many ‘zero-cost abstractions’, which means that in Rust, abstractions cost as little as possible in order to make them work. The ownership system is a prime example of a zero-cost abstraction. All of the analysis we’ll talk about in this guide is <em>done at compile time</em>. You do not pay any run-time cost for any of these features.</p> <p>However, this system does have a certain cost: learning curve. Many new users to Rust experience something we like to call ‘fighting with the borrow checker’, where the Rust compiler refuses to compile a program that the author thinks is valid. This often happens because the programmer’s mental model of how ownership should work doesn’t match the actual rules that Rust implements. You probably will experience similar things at first. There is good news, however: more experienced Rust developers report that once they work with the rules of the ownership system for a period of time, they fight the borrow checker less and less.</p> <p>With that in mind, let’s learn about lifetimes.</p> <a class="header" href="lifetimes.html#lifetimes-1" id="lifetimes-1"><h1>Lifetimes</h1></a> <p>Lending out a reference to a resource that someone else owns can be complicated. For example, imagine this set of operations:</p> <ol> <li>I acquire a handle to some kind of resource.</li> <li>I lend you a reference to the resource.</li> <li>I decide I’m done with the resource, and deallocate it, while you still have your reference.</li> <li>You decide to use the resource.</li> </ol> <p>Uh oh! Your reference is pointing to an invalid resource. This is called a dangling pointer or ‘use after free’, when the resource is memory. A small example of such a situation would be:</p> <pre><code class="language-rust ignore">let r; // Introduce reference: `r`. { let i = 1; // Introduce scoped value: `i`. r = &i; // Store reference of `i` in `r`. } // `i` goes out of scope and is dropped. println!("{}", r); // `r` still refers to `i`. </code></pre> <p>To fix this, we have to make sure that step four never happens after step three. In the small example above the Rust compiler is able to report the issue as it can see the lifetimes of the various values in the function.</p> <p>When we have a function that takes arguments by reference the situation becomes more complex. Consider the following example:</p> <pre><code class="language-rust ignore">fn skip_prefix(line: &str, prefix: &str) -> &str { // ... # line } let line = "lang:en=Hello World!"; let lang = "en"; let v; { let p = format!("lang:{}=", lang); // -+ `p` comes into scope. v = skip_prefix(line, p.as_str()); // | } // -+ `p` goes out of scope. println!("{}", v); </code></pre> <p>Here we have a function <code>skip_prefix</code> which takes two <code>&str</code> references as parameters and returns a single <code>&str</code> reference. We call it by passing in references to <code>line</code> and <code>p</code>: Two variables with different lifetimes. Now the safety of the <code>println!</code>-line depends on whether the reference returned by <code>skip_prefix</code> function references the still living <code>line</code> or the already dropped <code>p</code> string.</p> <p>Because of the above ambiguity, Rust will refuse to compile the example code. To get it to compile we need to tell the compiler more about the lifetimes of the references. This can be done by making the lifetimes explicit in the function declaration:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { fn skip_prefix<'a, 'b>(line: &'a str, prefix: &'b str) -> &'a str { // ... # line } #}</code></pre></pre> <p>Let's examine the changes without going too deep into the syntax for now - we'll get to that later. The first change was adding the <code><'a, 'b></code> after the method name. This introduces two lifetime parameters: <code>'a</code> and <code>'b</code>. Next, each reference in the function signature was associated with one of the lifetime parameters by adding the lifetime name after the <code>&</code>. This tells the compiler how the lifetimes between different references are related.</p> <p>As a result the compiler is now able to deduce that the return value of <code>skip_prefix</code> has the same lifetime as the <code>line</code> parameter, which makes the <code>v</code> reference safe to use even after the <code>p</code> goes out of scope in the original example.</p> <p>In addition to the compiler being able to validate the usage of <code>skip_prefix</code> return value, it can also ensure that the implementation follows the contract established by the function declaration. This is useful especially when you are implementing traits that are introduced <a href="traits.html">later in the book</a>.</p> <p><strong>Note</strong> It's important to understand that lifetime annotations are <em>descriptive</em>, not <em>prescriptive</em>. This means that how long a reference is valid is determined by the code, not by the annotations. The annotations, however, give information about lifetimes to the compiler that uses them to check the validity of references. The compiler can do so without annotations in simple cases, but needs the programmer's support in complex scenarios.</p> <a class="header" href="lifetimes.html#syntax" id="syntax"><h1>Syntax</h1></a> <p>The <code>'a</code> reads ‘the lifetime a’. Technically, every reference has some lifetime associated with it, but the compiler lets you elide (i.e. omit, see <a href="lifetimes.html#lifetime-elision">"Lifetime Elision"</a> below) them in common cases. Before we get to that, though, let’s look at a short example with explicit lifetimes:</p> <pre><code class="language-rust ignore">fn bar<'a>(...) </code></pre> <p>We previously talked a little about <a href="functions.html">function syntax</a>, but we didn’t discuss the <code><></code>s after a function’s name. A function can have ‘generic parameters’ between the <code><></code>s, of which lifetimes are one kind. We’ll discuss other kinds of generics <a href="generics.html">later in the book</a>, but for now, let’s focus on the lifetimes aspect.</p> <p>We use <code><></code> to declare our lifetimes. This says that <code>bar</code> has one lifetime, <code>'a</code>. If we had two reference parameters with different lifetimes, it would look like this:</p> <pre><code class="language-rust ignore">fn bar<'a, 'b>(...) </code></pre> <p>Then in our parameter list, we use the lifetimes we’ve named:</p> <pre><code class="language-rust ignore">...(x: &'a i32) </code></pre> <p>If we wanted a <code>&mut</code> reference, we’d do this:</p> <pre><code class="language-rust ignore">...(x: &'a mut i32) </code></pre> <p>If you compare <code>&mut i32</code> to <code>&'a mut i32</code>, they’re the same, it’s that the lifetime <code>'a</code> has snuck in between the <code>&</code> and the <code>mut i32</code>. We read <code>&mut i32</code> as ‘a mutable reference to an <code>i32</code>’ and <code>&'a mut i32</code> as ‘a mutable reference to an <code>i32</code> with the lifetime <code>'a</code>’.</p> <a class="header" href="lifetimes.html#in-structs" id="in-structs"><h1>In <code>struct</code>s</h1></a> <p>You’ll also need explicit lifetimes when working with <a href="structs.html"><code>struct</code></a>s that contain references:</p> <pre><pre class="playpen"><code class="language-rust">struct Foo<'a> { x: &'a i32, } fn main() { let y = &5; // This is the same as `let _y = 5; let y = &_y;`. let f = Foo { x: y }; println!("{}", f.x); } </code></pre></pre> <p>As you can see, <code>struct</code>s can also have lifetimes. In a similar way to functions,</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { struct Foo<'a> { # x: &'a i32, # } #}</code></pre></pre> <p>declares a lifetime, and</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { # struct Foo<'a> { x: &'a i32, # } #}</code></pre></pre> <p>uses it. So why do we need a lifetime here? We need to ensure that any reference to a <code>Foo</code> cannot outlive the reference to an <code>i32</code> it contains.</p> <a class="header" href="lifetimes.html#impl-blocks" id="impl-blocks"><h2><code>impl</code> blocks</h2></a> <p>Let’s implement a method on <code>Foo</code>:</p> <pre><pre class="playpen"><code class="language-rust">struct Foo<'a> { x: &'a i32, } impl<'a> Foo<'a> { fn x(&self) -> &'a i32 { self.x } } fn main() { let y = &5; // This is the same as `let _y = 5; let y = &_y;`. let f = Foo { x: y }; println!("x is: {}", f.x()); } </code></pre></pre> <p>As you can see, we need to declare a lifetime for <code>Foo</code> in the <code>impl</code> line. We repeat <code>'a</code> twice, like on functions: <code>impl<'a></code> defines a lifetime <code>'a</code>, and <code>Foo<'a></code> uses it.</p> <a class="header" href="lifetimes.html#multiple-lifetimes" id="multiple-lifetimes"><h2>Multiple lifetimes</h2></a> <p>If you have multiple references, you can use the same lifetime multiple times:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { fn x_or_y<'a>(x: &'a str, y: &'a str) -> &'a str { # x # } #}</code></pre></pre> <p>This says that <code>x</code> and <code>y</code> both are alive for the same scope, and that the return value is also alive for that scope. If you wanted <code>x</code> and <code>y</code> to have different lifetimes, you can use multiple lifetime parameters:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { fn x_or_y<'a, 'b>(x: &'a str, y: &'b str) -> &'a str { # x # } #}</code></pre></pre> <p>In this example, <code>x</code> and <code>y</code> have different valid scopes, but the return value has the same lifetime as <code>x</code>.</p> <a class="header" href="lifetimes.html#thinking-in-scopes" id="thinking-in-scopes"><h2>Thinking in scopes</h2></a> <p>A way to think about lifetimes is to visualize the scope that a reference is valid for. For example:</p> <pre><pre class="playpen"><code class="language-rust">fn main() { let y = &5; // -+ `y` comes into scope. // | // Stuff... // | // | } // -+ `y` goes out of scope. </code></pre></pre> <p>Adding in our <code>Foo</code>:</p> <pre><pre class="playpen"><code class="language-rust">struct Foo<'a> { x: &'a i32, } fn main() { let y = &5; // -+ `y` comes into scope. let f = Foo { x: y }; // -+ `f` comes into scope. // | // Stuff... // | // | } // -+ `f` and `y` go out of scope. </code></pre></pre> <p>Our <code>f</code> lives within the scope of <code>y</code>, so everything works. What if it didn’t? This code won’t work:</p> <pre><code class="language-rust ignore">struct Foo<'a> { x: &'a i32, } fn main() { let x; // -+ `x` comes into scope. // | { // | let y = &5; // ---+ `y` comes into scope. let f = Foo { x: y }; // ---+ `f` comes into scope. x = &f.x; // | | This causes an error. } // ---+ `f` and y go out of scope. // | println!("{}", x); // | } // -+ `x` goes out of scope. </code></pre> <p>Whew! As you can see here, the scopes of <code>f</code> and <code>y</code> are smaller than the scope of <code>x</code>. But when we do <code>x = &f.x</code>, we make <code>x</code> a reference to something that’s about to go out of scope.</p> <p>Named lifetimes are a way of giving these scopes a name. Giving something a name is the first step towards being able to talk about it.</p> <a class="header" href="lifetimes.html#static" id="static"><h2>'static</h2></a> <p>The lifetime named ‘static’ is a special lifetime. It signals that something has the lifetime of the entire program. Most Rust programmers first come across <code>'static</code> when dealing with strings:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { let x: &'static str = "Hello, world."; #}</code></pre></pre> <p>String literals have the type <code>&'static str</code> because the reference is always alive: they are baked into the data segment of the final binary. Another example are globals:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { static FOO: i32 = 5; let x: &'static i32 = &FOO; #}</code></pre></pre> <p>This adds an <code>i32</code> to the data segment of the binary, and <code>x</code> is a reference to it.</p> <a class="header" href="lifetimes.html#lifetime-elision" id="lifetime-elision"><h2>Lifetime Elision</h2></a> <p>Rust supports powerful local type inference in the bodies of functions, but it deliberately does not perform any reasoning about types for item signatures. However, for ergonomic reasons, a very restricted secondary inference algorithm called “lifetime elision” does apply when judging lifetimes. Lifetime elision is concerned solely with inferring lifetime parameters using three easily memorizable and unambiguous rules. This means lifetime elision acts as a shorthand for writing an item signature, while not hiding away the actual types involved as full local inference would if applied to it.</p> <p>When talking about lifetime elision, we use the terms <em>input lifetime</em> and <em>output lifetime</em>. An <em>input lifetime</em> is a lifetime associated with a parameter of a function, and an <em>output lifetime</em> is a lifetime associated with the return value of a function. For example, this function has an input lifetime:</p> <pre><code class="language-rust ignore">fn foo<'a>(bar: &'a str) </code></pre> <p>This one has an output lifetime:</p> <pre><code class="language-rust ignore">fn foo<'a>() -> &'a str </code></pre> <p>This one has a lifetime in both positions:</p> <pre><code class="language-rust ignore">fn foo<'a>(bar: &'a str) -> &'a str </code></pre> <p>Here are the three rules:</p> <ul> <li> <p>Each elided lifetime in a function’s arguments becomes a distinct lifetime parameter.</p> </li> <li> <p>If there is exactly one input lifetime, elided or not, that lifetime is assigned to all elided lifetimes in the return values of that function.</p> </li> <li> <p>If there are multiple input lifetimes, but one of them is <code>&self</code> or <code>&mut self</code>, the lifetime of <code>self</code> is assigned to all elided output lifetimes.</p> </li> </ul> <p>Otherwise, it is an error to elide an output lifetime.</p> <a class="header" href="lifetimes.html#examples" id="examples"><h3>Examples</h3></a> <p>Here are some examples of functions with elided lifetimes. We’ve paired each example of an elided lifetime with its expanded form.</p> <pre><code class="language-rust ignore">fn print(s: &str); // elided fn print<'a>(s: &'a str); // expanded fn debug(lvl: u32, s: &str); // elided fn debug<'a>(lvl: u32, s: &'a str); // expanded </code></pre> <p>In the preceding example, <code>lvl</code> doesn’t need a lifetime because it’s not a reference (<code>&</code>). Only things relating to references (such as a <code>struct</code> which contains a reference) need lifetimes.</p> <pre><code class="language-rust ignore">fn substr(s: &str, until: u32) -> &str; // elided fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded fn get_str() -> &str; // ILLEGAL, no inputs fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is ambiguous fn get_mut(&mut self) -> &mut T; // elided fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded fn args<T: ToCStr>(&mut self, args: &[T]) -> &mut Command; // elided fn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded fn new(buf: &mut [u8]) -> BufWriter; // elided fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>; // expanded </code></pre> </main> <nav class="nav-wrapper" aria-label="Page navigation"> <!-- Mobile navigation buttons --> <a rel="prev" href="references-and-borrowing.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> <i class="fa fa-angle-left"></i> </a> <a rel="next" href="mutability.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> <i class="fa fa-angle-right"></i> </a> <div style="clear: both"></div> </nav> </div> </div> <nav class="nav-wide-wrapper" aria-label="Page navigation"> <a href="references-and-borrowing.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> <i class="fa fa-angle-left"></i> </a> <a href="mutability.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> <i class="fa fa-angle-right"></i> </a> </nav> </div> <script src="searchindex.js" type="text/javascript" charset="utf-8"></script> <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script> <script src="mark.min.js" type="text/javascript" charset="utf-8"></script> <script src="searcher.js" type="text/javascript" charset="utf-8"></script> <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script> <script src="highlight.js" type="text/javascript" charset="utf-8"></script> <script src="book.js" type="text/javascript" charset="utf-8"></script> <!-- Custom JS scripts --> </body> </html>