Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 564935689ab5527f955e5449ded02799 > files > 262

rust-doc-1.19.0-1.mga6.armv7hl.rpm

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Validating References with 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">

        <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 rel="shortcut icon" href="favicon.png">

        <!-- Font Awesome -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <style>
            .page-wrapper.has-warning > .nav-chapters {
              /* add height for warning content & margin */
              top: 120px;
            }

            p.warning {
                background-color: rgb(242, 222, 222);
                border-bottom-color: rgb(238, 211, 215);
                border-bottom-left-radius: 4px;
                border-bottom-right-radius: 4px;
                border-bottom-style: solid;
                border-bottom-width: 0.666667px;
                border-image-outset: 0 0 0 0;
                border-image-repeat: stretch stretch;
                border-image-slice: 100% 100% 100% 100%;
                border-image-source: none;
                border-image-width: 1 1 1 1;
                border-left-color: rgb(238, 211, 215);
                border-left-style: solid;
                border-left-width: 0.666667px;
                border-right-color: rgb(238, 211, 215);
                border-right-style: solid;
                border-right-width: 0.666667px;
                border-top-color: rgb(238, 211, 215);
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                border-top-style: solid;
                border-top-width: 0.666667px;
                color: rgb(185, 74, 72);
                margin-bottom: 0px;
                margin-left: 0px;
                margin-right: 0px;
                margin-top: 30px;
                padding-bottom: 8px;
                padding-left: 14px;
                padding-right: 35px;
                padding-top: 8px;
            }
            p.warning strong {
                color: rgb(185, 74, 72)
            }
            p.warning a {
                color: rgb(0, 136, 204)
            }
        </style>

        <!-- MathJax -->
        <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

        <!-- Fetch JQuery from CDN but have a local fallback -->
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script>
            if (typeof jQuery == 'undefined') {
                document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
            }
        </script>
    </head>
    <body class="light">
        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme = localStorage.getItem('theme');
            if (theme == null) { theme = 'light'; }
            $('body').removeClass().addClass(theme);
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var sidebar = localStorage.getItem('sidebar');
            if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
            else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
        </script>

        <div id="sidebar" class="sidebar">
            <ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References &amp; Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Using Structs to Structure Related Data</a></li><li><ul class="section"><li><a href="ch05-01-defining-structs.html"><strong>5.1.</strong> Defining and Instantiating Structs</a></li><li><a href="ch05-02-example-structs.html"><strong>5.2.</strong> An Example Program Using Structs</a></li><li><a href="ch05-03-method-syntax.html"><strong>5.3.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums and Pattern Matching</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> Defining an Enum</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> The <code>match</code> Control Flow Operator</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> Concise Control Flow with <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-common-collections.html"><strong>8.</strong> Common Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generic Types, Traits, and Lifetimes</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Generic Data Types</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits: Defining Shared Behavior</a></li><li><a href="ch10-03-lifetime-syntax.html" class="active"><strong>10.3.</strong> Validating References with Lifetimes</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><a href="ch12-00-an-io-project.html"><strong>12.</strong> An I/O Project</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> Accepting Command Line Arguments</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> Reading a File</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> Improving Error Handling and Modularity</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> Testing the Library's Functionality</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> Working with Environment Variables</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> Writing to <code>stderr</code> instead of <code>stdout</code></a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Functional Language Features in Rust</a></li><li><ul class="section"><li><a href="ch13-01-closures.html"><strong>13.1.</strong> Closures</a></li><li><a href="ch13-02-iterators.html"><strong>13.2.</strong> Iterators</a></li><li><a href="ch13-03-improving-our-io-project.html"><strong>13.3.</strong> Improving our I/O Project</a></li><li><a href="ch13-04-performance.html"><strong>13.4.</strong> Performance</a></li></ul></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></li><li><ul class="section"><li><a href="ch14-01-release-profiles.html"><strong>14.1.</strong> Release Profiles</a></li><li><a href="ch14-02-publishing-to-crates-io.html"><strong>14.2.</strong> Publishing a Crate to Crates.io</a></li><li><a href="ch14-03-cargo-workspaces.html"><strong>14.3.</strong> Cargo Workspaces</a></li><li><a href="ch14-04-installing-binaries.html"><strong>14.4.</strong> Installing Binaries from Crates.io with <code>cargo install</code></a></li><li><a href="ch14-05-extending-cargo.html"><strong>14.5.</strong> Extending Cargo with Custom Commands</a></li></ul></li><li><a href="ch15-00-smart-pointers.html"><strong>15.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="ch15-01-box.html"><strong>15.1.</strong> <code>Box&lt;T&gt;</code> Points to Data on the Heap and Has a Known Size</a></li><li><a href="ch15-02-deref.html"><strong>15.2.</strong> The <code>Deref</code> Trait Allows Access to the Data Through a Reference</a></li><li><a href="ch15-03-drop.html"><strong>15.3.</strong> The <code>Drop</code> Trait Runs Code on Cleanup</a></li><li><a href="ch15-04-rc.html"><strong>15.4.</strong> <code>Rc&lt;T&gt;</code>, the Reference Counted Smart Pointer</a></li><li><a href="ch15-05-interior-mutability.html"><strong>15.5.</strong> <code>RefCell&lt;T&gt;</code> and the Interior Mutability Pattern</a></li><li><a href="ch15-06-reference-cycles.html"><strong>15.6.</strong> Creating Reference Cycles and Leaking Memory is Safe</a></li></ul></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> Fearless Concurrency</a></li><li><ul class="section"><li><a href="ch16-01-threads.html"><strong>16.1.</strong> Threads</a></li><li><a href="ch16-02-message-passing.html"><strong>16.2.</strong> Message Passing</a></li><li><a href="ch16-03-shared-state.html"><strong>16.3.</strong> Shared State</a></li><li><a href="ch16-04-extensible-concurrency-sync-and-send.html"><strong>16.4.</strong> Extensible Concurrency: <code>Sync</code> and <code>Send</code></a></li></ul></li><li><a href="ch17-00-oop.html"><strong>17.</strong> Is Rust an Object-Oriented Programming Language?</a></li><li><ul class="section"><li><a href="ch17-01-what-is-oo.html"><strong>17.1.</strong> What Does Object-Oriented Mean?</a></li><li><a href="ch17-02-trait-objects.html"><strong>17.2.</strong> Trait Objects for Using Values of Different Types</a></li><li><a href="ch17-03-oo-design-patterns.html"><strong>17.3.</strong> Object-Oriented Design Pattern Implementations</a></li></ul></li><li><a href="ch18-00-patterns.html"><strong>18.</strong> Patterns Match the Structure of Values</a></li><li><ul class="section"><li><a href="ch18-01-all-the-places-for-patterns.html"><strong>18.1.</strong> All the Places Patterns May be Used</a></li><li><a href="ch18-02-refutability.html"><strong>18.2.</strong> Refutability: Whether a Pattern Might Fail to Match</a></li><li><a href="ch18-03-pattern-syntax.html"><strong>18.3.</strong> All the Pattern Syntax</a></li></ul></li><li><a href="ch19-00-advanced-features.html"><strong>19.</strong> Advanced Features</a></li><li><ul class="section"><li><a href="ch19-01-unsafe-rust.html"><strong>19.1.</strong> Unsafe Rust</a></li><li><a href="ch19-02-advanced-lifetimes.html"><strong>19.2.</strong> Advanced Lifetimes</a></li><li><a href="ch19-03-advanced-traits.html"><strong>19.3.</strong> Advanced Traits</a></li><li><a href="ch19-04-advanced-types.html"><strong>19.4.</strong> Advanced Types</a></li><li><a href="ch19-05-advanced-functions-and-closures.html"><strong>19.5.</strong> Advanced Functions &amp; Closures</a></li></ul></li><li><a href="ch20-00-final-project-a-web-server.html"><strong>20.</strong> Final Project: Building a Multithreaded Web Server</a></li><li><ul class="section"><li><a href="ch20-01-single-threaded.html"><strong>20.1.</strong> A Single Threaded Web Server</a></li><li><a href="ch20-02-slow-requests.html"><strong>20.2.</strong> How Slow Requests Affect Throughput</a></li><li><a href="ch20-03-designing-the-interface.html"><strong>20.3.</strong> Designing the Thread Pool Interface</a></li><li><a href="ch20-04-storing-threads.html"><strong>20.4.</strong> Creating the Thread Pool and Storing Threads</a></li><li><a href="ch20-05-sending-requests-via-channels.html"><strong>20.5.</strong> Sending Requests to Threads Via Channels</a></li><li><a href="ch20-06-graceful-shutdown-and-cleanup.html"><strong>20.6.</strong> Graceful Shutdown and Cleanup</a></li></ul></li><li><a href="appendix-00.html"><strong>21.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>21.1.</strong> A - Keywords</a></li><li><a href="appendix-02-operators.html"><strong>21.2.</strong> B - Operators</a></li><li><strong>21.3.</strong> C - Derivable Traits</li><li><strong>21.4.</strong> D - Nightly Rust</li><li><strong>21.5.</strong> E - Macros</li><li><strong>21.6.</strong> F - Translations</li><li><a href="appendix-07-newest-features.html"><strong>21.7.</strong> G - Newest Features</a></li></ul></li></ul>
        </div>

        <div id="page-wrapper" class="page-wrapper has-warning">

            <div class="page">
                <header><p class="warning">You are reading a <strong>draft</strong> of the next edition of TRPL. For more, go <a href="../index.html">here</a>.</p></header>
                <div id="menu-bar" class="menu-bar">
                    <div class="left-buttons">
                        <i id="sidebar-toggle" class="fa fa-bars"></i>
                        <i id="theme-toggle" class="fa fa-paint-brush"></i>
                    </div>

                    <h1 class="menu-title">The Rust Programming Language</h1>

                    <div class="right-buttons">
                        <i id="print-button" class="fa fa-print" title="Print this book"></i>
                    </div>
                </div>


                <div id="content" class="content">
                    <a class="header" href="ch10-03-lifetime-syntax.html#validating-references-with-lifetimes" id="validating-references-with-lifetimes"><h2>Validating References with Lifetimes</h2></a>
<p>When we talked about references in Chapter 4, we left out an important detail:
every reference in Rust has a <em>lifetime</em>, which is the scope for which that
reference is valid. Most of the time lifetimes are implicit and inferred, just
like most of the time types are inferred. Similarly to when we have to annotate
types because multiple types are possible, there are cases where the lifetimes
of references could be related in a few different ways, so Rust needs us to
annotate the relationships using generic lifetime parameters so that it can
make sure the actual references used at runtime will definitely be valid.</p>
<p>Yes, it's a bit unusual, and will be different to tools you've used in other
programming languages. Lifetimes are, in some ways, Rust's most distinctive
feature.</p>
<p>Lifetimes are a big topic that can't be covered in entirety in this chapter, so
we'll cover common ways you might encounter lifetime syntax in this chapter to
get you familiar with the concepts. Chapter 19 will contain more advanced
information about everything lifetimes can do.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#lifetimes-prevent-dangling-references" id="lifetimes-prevent-dangling-references"><h3>Lifetimes Prevent Dangling References</h3></a>
<p>The main aim of lifetimes is to prevent dangling references, which will cause a
program to reference data other than the data we're intending to reference.
Consider the program in Listing 10-16, with an outer scope and an inner scope.
The outer scope declares a variable named <code>r</code> with no initial value, and the
inner scope declares a variable named <code>x</code> with the initial value of 5. Inside
the inner scope, we attempt to set the value of <code>r</code> as a reference to <code>x</code>. Then
the inner scope ends, and we attempt to print out the value in <code>r</code>:</p>
<pre><code class="language-rust ignore">{
    let r;

    {
        let x = 5;
        r = &amp;x;
    }

    println!(&quot;r: {}&quot;, r);
}
</code></pre>
<p><span class="caption">Listing 10-16: An attempt to use a reference whose value
has gone out of scope</span></p>
<blockquote>
<a class="header" href="ch10-03-lifetime-syntax.html#uninitialized-variables-cannot-be-used" id="uninitialized-variables-cannot-be-used"><h4>Uninitialized Variables Cannot Be Used</h4></a>
<p>The next few examples declare variables without giving them an initial value,
so that the variable name exists in the outer scope. This might appear to be
in conflict with Rust not having null. However, if we try to use a variable
before giving it a value, we'll get a compile-time error. Try it out!</p>
</blockquote>
<p>When we compile this code, we'll get an error:</p>
<pre><code class="language-text">error: `x` does not live long enough
   |
6  |         r = &amp;x;
   |              - borrow occurs here
7  |     }
   |     ^ `x` dropped here while still borrowed
...
10 | }
   | - borrowed value needs to live until here
</code></pre>
<p>The variable <code>x</code> doesn't &quot;live long enough.&quot; Why not? Well, <code>x</code> is going to go
out of scope when we hit the closing curly brace on line 7, ending the inner
scope. But <code>r</code> is valid for the outer scope; its scope is larger and we say
that it &quot;lives longer.&quot; If Rust allowed this code to work, <code>r</code> would be
referencing memory that was deallocated when <code>x</code> went out of scope, and
anything we tried to do with <code>r</code> wouldn't work correctly. So how does Rust
determine that this code should not be allowed?</p>
<a class="header" href="ch10-03-lifetime-syntax.html#the-borrow-checker" id="the-borrow-checker"><h4>The Borrow Checker</h4></a>
<p>The part of the compiler called the <em>borrow checker</em> compares scopes to
determine that all borrows are valid. Listing 10-17 shows the same example from
Listing 10-16 with annotations showing the lifetimes of the variables:</p>
<pre><code class="language-rust ignore">{
    let r;         // -------+-- 'a
                   //        |
    {              //        |
        let x = 5; // -+-----+-- 'b
        r = &amp;x;    //  |     |
    }              // -+     |
                   //        |
    println!(&quot;r: {}&quot;, r); // |
                   //        |
                   // -------+
}
</code></pre>
<p><span class="caption">Listing 10-17: Annotations of the lifetimes of <code>r</code> and
<code>x</code>, named <code>'a</code> and <code>'b</code> respectively</span></p>
<!-- Just checking I'm reading this right: the inside block is the b lifetime,
correct? I want to leave a note for production, make sure we can make that
clear -->
<!-- Yes, the inside block for the `'b` lifetime starts with the `let x = 5;`
line and ends with the first closing curly brace on the 7th line. Do you think
the text art comments work or should we make an SVG diagram that has nicer
looking arrows and labels? /Carol -->
<p>We've annotated the lifetime of <code>r</code> with <code>'a</code> and the lifetime of <code>x</code> with
<code>'b</code>. As you can see, the inner <code>'b</code> block is much smaller than the outer <code>'a</code>
lifetime block. At compile time, Rust compares the size of the two lifetimes
and sees that <code>r</code> has a lifetime of <code>'a</code>, but that it refers to an object with
a lifetime of <code>'b</code>. The program is rejected because the lifetime <code>'b</code> is
shorter than the lifetime of <code>'a</code>: the subject of the reference does not live
as long as the reference.</p>
<p>Let's look at an example in Listing 10-18 that doesn't try to make a dangling
reference and compiles without any errors:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
{
    let x = 5;            // -----+-- 'b
                          //      |
    let r = &amp;x;           // --+--+-- 'a
                          //   |  |
    println!(&quot;r: {}&quot;, r); //   |  |
                          // --+  |
}                         // -----+

#}</code></pre></pre>
<p><span class="caption">Listing 10-18: A valid reference because the data has a
longer lifetime than the reference</span></p>
<p>Here, <code>x</code> has the lifetime <code>'b</code>, which in this case is larger than <code>'a</code>. This
means <code>r</code> can reference <code>x</code>: Rust knows that the reference in <code>r</code> will always
be valid while <code>x</code> is valid.</p>
<p>Now that we've shown where the lifetimes of references are in a concrete
example and discussed how Rust analyzes lifetimes to ensure references will
always be valid, let's talk about generic lifetimes of parameters and return
values in the context of functions.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#generic-lifetimes-in-functions" id="generic-lifetimes-in-functions"><h3>Generic Lifetimes in Functions</h3></a>
<p>Let's write a function that will return the longest of two string slices. We
want to be able to call this function by passing it two string slices, and we
want to get back a string slice. The code in Listing 10-19 should print <code>The longest string is abcd</code> once we've implemented the <code>longest</code> function:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">fn main() {
    let string1 = String::from(&quot;abcd&quot;);
    let string2 = &quot;xyz&quot;;

    let result = longest(string1.as_str(), string2);
    println!(&quot;The longest string is {}&quot;, result);
}
</code></pre>
<p><span class="caption">Listing 10-19: A <code>main</code> function that calls the <code>longest</code>
function to find the longest of two string slices</span></p>
<p>Note that we want the function to take string slices (which are references, as
we talked about in Chapter 4) since we don't want the <code>longest</code> function to
take ownership of its arguments. We want the function to be able to accept
slices of a <code>String</code> (which is the type of the variable <code>string1</code>) as well as
string literals (which is what variable <code>string2</code> contains).</p>
<!-- why is `a` a slice and `b` a literal? You mean "a" from the string "abcd"? -->
<!-- I've changed the variable names to remove ambiguity between the variable
name `a` and the "a" from the string "abcd". `string1` is not a slice, it's a
`String`, but we're going to pass a slice that refers to that `String` to the
`longest` function (`string1.as_str()` creates a slice that references the
`String` stored in `string1`). We chose to have `string2` be a literal since
the reader might have code with both `String`s and string literals, and the way
most readers first get into problems with lifetimes is involving string slices,
so we wanted to demonstrate the flexibility of taking string slices as
arguments but the issues you might run into because string slices are
references.
All of the `String`/string slice/string literal concepts here are covered
thoroughly in Chapter 4, which is why we put two back references here (above
and below). If these topics are confusing you in this context, I'd be
interested to know if rereading Chapter 4 clears up that confusion.
/Carol -->
<p>Refer back to the &quot;String Slices as Arguments&quot; section of Chapter 4 for more
discussion about why these are the arguments we want.</p>
<p>If we try to implement the <code>longest</code> function as shown in Listing 10-20, it
won't compile:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
    if x.len() &gt; y.len() {
        x
    } else {
        y
    }
}
</code></pre>
<p><span class="caption">Listing 10-20: An implementation of the <code>longest</code>
function that returns the longest of two string slices, but does not yet
compile</span></p>
<p>Instead we get the following error that talks about lifetimes:</p>
<pre><code class="language-text">error[E0106]: missing lifetime specifier
   |
1  | fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
   |                                 ^ expected lifetime parameter
   |
   = help: this function's return type contains a borrowed value, but the
   signature does not say whether it is borrowed from `x` or `y`
</code></pre>
<p>The help text is telling us that the return type needs a generic lifetime
parameter on it because Rust can't tell if the reference being returned refers
to <code>x</code> or <code>y</code>. Actually, we don't know either, since the <code>if</code> block in the body
of this function returns a reference to <code>x</code> and the <code>else</code> block returns a
reference to <code>y</code>!</p>
<p>As we're defining this function, we don't know the concrete values that will be
passed into this function, so we don't know whether the <code>if</code> case or the <code>else</code>
case will execute. We also don't know the concrete lifetimes of the references
that will be passed in, so we can't look at the scopes like we did in Listings
10-17 and 10-18 in order to determine that the reference we return will always
be valid. The borrow checker can't determine this either, because it doesn't
know how the lifetimes of <code>x</code> and <code>y</code> relate to the lifetime of the return
value. We're going to add generic lifetime parameters that will define the
relationship between the references so that the borrow checker can perform its
analysis.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#lifetime-annotation-syntax" id="lifetime-annotation-syntax"><h3>Lifetime Annotation Syntax</h3></a>
<p>Lifetime annotations don't change how long any of the references involved live.
In the same way that functions can accept any type when the signature specifies
a generic type parameter, functions can accept references with any lifetime
when the signature specifies a generic lifetime parameter. What lifetime
annotations do is relate the lifetimes of multiple references to each other.</p>
<p>Lifetime annotations have a slightly unusual syntax: the names of lifetime
parameters must start with an apostrophe <code>'</code>. The names of lifetime parameters
are usually all lowercase, and like generic types, their names are usually very
short. <code>'a</code> is the name most people use as a default. Lifetime parameter
annotations go after the <code>&amp;</code> of a reference, and a space separates the lifetime
annotation from the reference's type.</p>
<p>Here's some examples: we've got a reference to an <code>i32</code> without a lifetime
parameter, a reference to an <code>i32</code> that has a lifetime parameter named <code>'a</code>,
and a mutable reference to an <code>i32</code> that also has the lifetime <code>'a</code>:</p>
<pre><code class="language-rust ignore">&amp;i32        // a reference
&amp;'a i32     // a reference with an explicit lifetime
&amp;'a mut i32 // a mutable reference with an explicit lifetime
</code></pre>
<p>One lifetime annotation by itself doesn't have much meaning: lifetime
annotations tell Rust how the generic lifetime parameters of multiple
references relate to each other. If we have a function with the parameter
<code>first</code> that is a reference to an <code>i32</code> that has the lifetime <code>'a</code>, and the
function has another parameter named <code>second</code> that is another reference to an
<code>i32</code> that also has the lifetime <code>'a</code>, these two lifetime annotations that have
the same name indicate that the references <code>first</code> and <code>second</code> must both live
as long as the same generic lifetime.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#lifetime-annotations-in-function-signatures" id="lifetime-annotations-in-function-signatures"><h3>Lifetime Annotations in Function Signatures</h3></a>
<p>Let's look at lifetime annotations in the context of the <code>longest</code> function
we're working on. Just like generic type parameters, generic lifetime
parameters need to be declared within angle brackets between the function name
and the parameter list. The constraint we want to tell Rust about for the
references in the parameters and the return value is that they all must have
the same lifetime, which we'll name <code>'a</code> and add to each reference as shown in
Listing 10-21:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
    if x.len() &gt; y.len() {
        x
    } else {
        y
    }
}

#}</code></pre></pre>
<p><span class="caption">Listing 10-21: The <code>longest</code> function definition that
specifies all the references in the signature must have the same lifetime,
<code>'a</code></span></p>
<p>This will compile and will produce the result we want when used with the <code>main</code>
function in Listing 10-19.</p>
<p>The function signature now says that for some lifetime <code>'a</code>, the function will
get two parameters, both of which are string slices that live at least as long
as the lifetime <code>'a</code>. The function will return a string slice that also will
last at least as long as the lifetime <code>'a</code>. This is the contract we are telling
Rust we want it to enforce.</p>
<p>By specifying the lifetime parameters in this function signature, we are not
changing the lifetimes of any values passed in or returned, but we are saying
that any values that do not adhere to this contract should be rejected by the
borrow checker. This function does not know (or need to know) exactly how long
<code>x</code> and <code>y</code> will live, but only needs to know that there is some scope that
can be substituted for <code>'a</code> that will satisfy this signature.</p>
<p>When annotating lifetimes in functions, the annotations go on the function
signature, and not in any of the code in the function body. This is because
Rust is able to analyze the code within the function without any help, but when
a function has references to or from code outside that function, the lifetimes
of the arguments or return values will potentially be different each time the
function is called. This would be incredibly costly and often impossible for
Rust to figure out. In this case, we need to annotate the lifetimes ourselves.</p>
<p>When concrete references are passed to <code>longest</code>, the concrete lifetime that
gets substituted for <code>'a</code> is the part of the scope of <code>x</code> that overlaps with
the scope of <code>y</code>. Since scopes always nest, another way to say this is that the
generic lifetime <code>'a</code> will get the concrete lifetime equal to the smaller of
the lifetimes of <code>x</code> and <code>y</code>. Because we've annotated the returned reference
with the same lifetime parameter <code>'a</code>, the returned reference will therefore be
guaranteed to be valid as long as the shorter of the lifetimes of <code>x</code> and <code>y</code>.</p>
<p>Let's see how this restricts the usage of the <code>longest</code> function by passing in
references that have different concrete lifetimes. Listing 10-22 is a
straightforward example that should match your intuition from any language:
<code>string1</code> is valid until the end of the outer scope, <code>string2</code> is valid until
the end of the inner scope, and <code>result</code> references something that is valid
until the end of the inner scope. The borrow checker approves of this code; it
will compile and print <code>The longest string is long string is long</code> when run:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
#     if x.len() &gt; y.len() {
#         x
#     } else {
#         y
#     }
# }
#
fn main() {
    let string1 = String::from(&quot;long string is long&quot;);

    {
        let string2 = String::from(&quot;xyz&quot;);
        let result = longest(string1.as_str(), string2.as_str());
        println!(&quot;The longest string is {}&quot;, result);
    }
}
</code></pre></pre>
<p><span class="caption">Listing 10-22: Using the <code>longest</code> function with
references to <code>String</code> values that have different concrete lifetimes</span></p>
<p>Next, let's try an example that will show that the lifetime of the reference in
<code>result</code> must be the smaller lifetime of the two arguments. We'll move the
declaration of the <code>result</code> variable outside the inner scope, but leave the
assignment of the value to the <code>result</code> variable inside the scope with
<code>string2</code>. Next, we'll move the <code>println!</code> that uses <code>result</code> outside of the
inner scope, after it has ended. The code in Listing 10-23 will not compile:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">fn main() {
    let string1 = String::from(&quot;long string is long&quot;);
    let result;
    {
        let string2 = String::from(&quot;xyz&quot;);
        result = longest(string1.as_str(), string2.as_str());
    }
    println!(&quot;The longest string is {}&quot;, result);
}
</code></pre>
<p><span class="caption">Listing 10-23: Attempting to use <code>result</code> after <code>string2</code>
has gone out of scope won't compile</span></p>
<p>If we try to compile this, we'll get this error:</p>
<pre><code class="language-text">error: `string2` does not live long enough
   |
6  |         result = longest(string1.as_str(), string2.as_str());
   |                                            ------- borrow occurs here
7  |     }
   |     ^ `string2` dropped here while still borrowed
8  |     println!(&quot;The longest string is {}&quot;, result);
9  | }
   | - borrowed value needs to live until here
</code></pre>
<p>The error is saying that in order for <code>result</code> to be valid for the <code>println!</code>,
<code>string2</code> would need to be valid until the end of the outer scope. Rust knows
this because we annotated the lifetimes of the function parameters and return
values with the same lifetime parameter, <code>'a</code>.</p>
<p>We can look at this code as humans and see that <code>string1</code> is longer, and
therefore <code>result</code> will contain a reference to <code>string1</code>. Because <code>string1</code> has
not gone out of scope yet, a reference to <code>string1</code> will still be valid for the
<code>println!</code>. However, what we've told Rust with the lifetime parameters is that
the lifetime of the reference returned by the <code>longest</code> function is the same as
the smaller of the lifetimes of the references passed in. Therefore, the borrow
checker disallows the code in Listing 10-23 as possibly having an invalid
reference.</p>
<p>Try designing some more experiments that vary the values and lifetimes of the
references passed in to the <code>longest</code> function and how the returned reference
is used. Make hypotheses about whether your experiments will pass the borrow
checker or not before you compile, then check to see if you're right!</p>
<a class="header" href="ch10-03-lifetime-syntax.html#thinking-in-terms-of-lifetimes" id="thinking-in-terms-of-lifetimes"><h3>Thinking in Terms of Lifetimes</h3></a>
<p>The exact way to specify lifetime parameters depends on what your function is
doing. For example, if we changed the implementation of the <code>longest</code> function
to always return the first argument rather than the longest string slice, we
wouldn't need to specify a lifetime on the <code>y</code> parameter. This code compiles:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;str) -&gt; &amp;'a str {
    x
}

#}</code></pre></pre>
<p>In this example, we've specified a lifetime parameter <code>'a</code> for the parameter
<code>x</code> and the return type, but not for the parameter <code>y</code>, since the lifetime of
<code>y</code> does not have any relationship with the lifetime of <code>x</code> or the return value.</p>
<p>When returning a reference from a function, the lifetime parameter for the
return type needs to match the lifetime parameter of one of the arguments. If
the reference returned does <em>not</em> refer to one of the arguments, the only other
possibility is that it refers to a value created within this function, which
would be a dangling reference since the value will go out of scope at the end
of the function. Consider this attempted implementation of the <code>longest</code>
function that won't compile:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">fn longest&lt;'a&gt;(x: &amp;str, y: &amp;str) -&gt; &amp;'a str {
    let result = String::from(&quot;really long string&quot;);
    result.as_str()
}
</code></pre>
<p>Even though we've specified a lifetime parameter <code>'a</code> for the return type, this
implementation fails to compile because the return value lifetime is not
related to the lifetime of the parameters at all. Here's the error message we
get:</p>
<pre><code class="language-text">error: `result` does not live long enough
  |
3 |     result.as_str()
  |     ^^^^^^ does not live long enough
4 | }
  | - borrowed value only lives until here
  |
note: borrowed value must be valid for the lifetime 'a as defined on the block
at 1:44...
  |
1 | fn longest&lt;'a&gt;(x: &amp;str, y: &amp;str) -&gt; &amp;'a str {
  |                                             ^
</code></pre>
<p>The problem is that <code>result</code> will go out of scope and get cleaned up at the end
of the <code>longest</code> function, and we're trying to return a reference to <code>result</code>
from the function. There's no way we can specify lifetime parameters that would
change the dangling reference, and Rust won't let us create a dangling
reference. In this case, the best fix would be to return an owned data type
rather than a reference so that the calling function is then responsible for
cleaning up the value.</p>
<p>Ultimately, lifetime syntax is about connecting the lifetimes of various
arguments and return values of functions. Once they're connected, Rust has
enough information to allow memory-safe operations and disallow operations that
would create dangling pointers or otherwise violate memory safety.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#lifetime-annotations-in-struct-definitions" id="lifetime-annotations-in-struct-definitions"><h3>Lifetime Annotations in Struct Definitions</h3></a>
<p>Up until now, we've only defined structs to hold owned types. It is possible
for structs to hold references, but we need to add a lifetime annotation on
every reference in the struct's definition. Listing 10-24 has a struct named
<code>ImportantExcerpt</code> that holds a string slice:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust">struct ImportantExcerpt&lt;'a&gt; {
    part: &amp;'a str,
}

fn main() {
    let novel = String::from(&quot;Call me Ishmael. Some years ago...&quot;);
    let first_sentence = novel.split('.')
        .next()
        .expect(&quot;Could not find a '.'&quot;);
    let i = ImportantExcerpt { part: first_sentence };
}
</code></pre></pre>
<p><span class="caption">Listing 10-24: A struct that holds a reference, so its
definition needs a lifetime annotation</span></p>
<p>This struct has one field, <code>part</code>, that holds a string slice, which is a
reference. Just like with generic data types, we have to declare the name of
the generic lifetime parameter inside angle brackets after the name of the
struct so that we can use the lifetime parameter in the body of the struct
definition.</p>
<p>The <code>main</code> function here creates an instance of the <code>ImportantExcerpt</code> struct
that holds a reference to the first sentence of the <code>String</code> owned by the
variable <code>novel</code>.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#lifetime-elision" id="lifetime-elision"><h3>Lifetime Elision</h3></a>
<p>In this section, we've learned that every reference has a lifetime, and we need
to specify lifetime parameters for functions or structs that use references.
However, in Chapter 4 we had a function in the &quot;String Slices&quot; section, shown
again in Listing 10-25, that compiled without lifetime annotations:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
fn first_word(s: &amp;str) -&gt; &amp;str {
    let bytes = s.as_bytes();

    for (i, &amp;item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &amp;s[0..i];
        }
    }

    &amp;s[..]
}

#}</code></pre></pre>
<p><span class="caption">Listing 10-25: A function we defined in Chapter 4 that
compiled without lifetime annotations, even though the parameter and return
type are references</span></p>
<p>The reason this function compiles without lifetime annotations is historical:
in early versions of pre-1.0 Rust, this indeed wouldn't have compiled. Every
reference needed an explicit lifetime. At that time, the function signature
would have been written like this:</p>
<pre><code class="language-rust ignore">fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;'a str {
</code></pre>
<p>After writing a lot of Rust code, the Rust team found that Rust programmers
were typing the same lifetime annotations over and over in particular
situations. These situations were predictable and followed a few deterministic
patterns. The Rust team then programmed these patterns into the Rust compiler's
code so that the borrow checker can infer the lifetimes in these situations
without forcing the programmer to explicitly add the annotations.</p>
<p>We mention this piece of Rust history because it's entirely possible that more
deterministic patterns will emerge and be added to the compiler. In the future,
even fewer lifetime annotations might be required.</p>
<p>The patterns programmed into Rust's analysis of references are called the
<em>lifetime elision rules</em>. These aren't rules for programmers to follow; the
rules are a set of particular cases that the compiler will consider, and if
your code fits these cases, you don't need to write the lifetimes explicitly.</p>
<p>The elision rules don't provide full inference: if Rust deterministically
applies the rules but there's still ambiguity as to what lifetimes the
references have, it won't guess what the lifetime of the remaining references
should be. In this case, the compiler will give you an error that can be
resolved by adding the lifetime annotations that correspond to your intentions
for how the references relate to each other.</p>
<p>First, some definitions: Lifetimes on function or method parameters are called
<em>input lifetimes</em>, and lifetimes on return values are called <em>output lifetimes</em>.</p>
<p>Now, on to the rules that the compiler uses to figure out what lifetimes
references have when there aren't explicit annotations. The first rule applies
to input lifetimes, and the second two rules apply to output lifetimes. If the
compiler gets to the end of the three rules and there are still references that
it can't figure out lifetimes for, the compiler will stop with an error.</p>
<ol>
<li>
<p>Each parameter that is a reference gets its own lifetime parameter. In other
words, a function with one parameter gets one lifetime parameter: <code>fn foo&lt;'a&gt;(x: &amp;'a i32)</code>, a function with two arguments gets two separate
lifetime parameters: <code>fn foo&lt;'a, 'b&gt;(x: &amp;'a i32, y: &amp;'b i32)</code>, and so on.</p>
</li>
<li>
<p>If there is exactly one input lifetime parameter, that lifetime is assigned
to all output lifetime parameters: <code>fn foo&lt;'a&gt;(x: &amp;'a i32) -&gt; &amp;'a i32</code>.</p>
</li>
<li>
<p>If there are multiple input lifetime parameters, but one of them is <code>&amp;self</code>
or <code>&amp;mut self</code> because this is a method, then the lifetime of <code>self</code> is
assigned to all output lifetime parameters. This makes writing methods much
nicer.</p>
</li>
</ol>
<p>Let's pretend we're the compiler and apply these rules to figure out what the
lifetimes of the references in the signature of the <code>first_word</code> function in
Listing 10-25 are. The signature starts without any lifetimes associated with
the references:</p>
<pre><code class="language-rust ignore">fn first_word(s: &amp;str) -&gt; &amp;str {
</code></pre>
<p>Then we (as the compiler) apply the first rule, which says each parameter gets
its own lifetime. We're going to call it <code>'a</code> as usual, so now the signature is:</p>
<pre><code class="language-rust ignore">fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;str {
</code></pre>
<p>On to the second rule, which applies because there is exactly one input
lifetime. The second rule says the lifetime of the one input parameter gets
assigned to the output lifetime, so now the signature is:</p>
<pre><code class="language-rust ignore">fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;'a str {
</code></pre>
<p>Now all the references in this function signature have lifetimes, and the
compiler can continue its analysis without needing the programmer to annotate
the lifetimes in this function signature.</p>
<p>Let's do another example, this time with the <code>longest</code> function that had no
lifetime parameters when we started working with in Listing 10-20:</p>
<pre><code class="language-rust ignore">fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
</code></pre>
<p>Pretending we're the compiler again, let's apply the first rule: each parameter
gets its own lifetime. This time we have two parameters, so we have two
lifetimes:</p>
<pre><code class="language-rust ignore">fn longest&lt;'a, 'b&gt;(x: &amp;'a str, y: &amp;'b str) -&gt; &amp;str {
</code></pre>
<p>Looking at the second rule, it doesn't apply since there is more than one input
lifetime. Looking at the third rule, this also does not apply because this is a
function rather than a method, so none of the parameters are <code>self</code>. So we're
out of rules, but we haven't figured out what the return type's lifetime is.
This is why we got an error trying to compile the code from Listing 10-20: the
compiler worked through the lifetime elision rules it knows, but still can't
figure out all the lifetimes of the references in the signature.</p>
<p>Because the third rule only really applies in method signatures, let's look at
lifetimes in that context now, and see why the third rule means we don't have
to annotate lifetimes in method signatures very often.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#lifetime-annotations-in-method-definitions" id="lifetime-annotations-in-method-definitions"><h3>Lifetime Annotations in Method Definitions</h3></a>
<!-- Is this different to the reference lifetime annotations, or just a
finalized explanation? -->
<!-- This is about lifetimes on references in method signatures, which is where
the 3rd lifetime elision rule kicks in. It can also be confusing where lifetime
parameters need to be declared and used since the lifetime parameters could go
with the struct's fields or with references passed into or returned from
methods. /Carol -->
<p>When we implement methods on a struct with lifetimes, the syntax is again the
same as that of generic type parameters that we showed in Listing 10-10: the
place that lifetime parameters are declared and used depends on whether the
lifetime parameter is related to the struct fields or the method arguments and
return values.</p>
<p>Lifetime names for struct fields always need to be declared after the <code>impl</code>
keyword and then used after the struct's name, since those lifetimes are part
of the struct's type.</p>
<p>In method signatures inside the <code>impl</code> block, references might be tied to the
lifetime of references in the struct's fields, or they might be independent. In
addition, the lifetime elision rules often make it so that lifetime annotations
aren't necessary in method signatures. Let's look at some examples using the
struct named <code>ImportantExcerpt</code> that we defined in Listing 10-24.</p>
<p>First, here's a method named <code>level</code>. The only parameter is a reference to
<code>self</code>, and the return value is just an <code>i32</code>, not a reference to anything:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# struct ImportantExcerpt&lt;'a&gt; {
#     part: &amp;'a str,
# }
#
impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
    fn level(&amp;self) -&gt; i32 {
        3
    }
}

#}</code></pre></pre>
<p>The lifetime parameter declaration after <code>impl</code> and use after the type name is
required, but we're not required to annotate the lifetime of the reference to
<code>self</code> because of the first elision rule.</p>
<p>Here's an example where the third lifetime elision rule applies:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# struct ImportantExcerpt&lt;'a&gt; {
#     part: &amp;'a str,
# }
#
impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
    fn announce_and_return_part(&amp;self, announcement: &amp;str) -&gt; &amp;str {
        println!(&quot;Attention please: {}&quot;, announcement);
        self.part
    }
}

#}</code></pre></pre>
<p>There are two input lifetimes, so Rust applies the first lifetime elision rule
and gives both <code>&amp;self</code> and <code>announcement</code> their own lifetimes. Then, because
one of the parameters is <code>&amp;self</code>, the return type gets the lifetime of <code>&amp;self</code>,
and all lifetimes have been accounted for.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#the-static-lifetime" id="the-static-lifetime"><h3>The Static Lifetime</h3></a>
<p>There is <em>one</em> special lifetime we need to discuss: <code>'static</code>. The <code>'static</code>
lifetime is the entire duration of the program. All string literals have the
<code>'static</code> lifetime, which we can choose to annotate as follows:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
let s: &amp;'static str = &quot;I have a static lifetime.&quot;;

#}</code></pre></pre>
<p>The text of this string is stored directly in the binary of your program and
the binary of your program is always available. Therefore, the lifetime of all
string literals is <code>'static</code>.</p>
<!-- How would you add a static lifetime (below)? -->
<!-- Just like you'd specify any lifetime, see above where it shows `&'static str`. /Carol -->
<p>You may see suggestions to use the <code>'static</code> lifetime in error message help
text, but before specifying <code>'static</code> as the lifetime for a reference, think
about whether the reference you have is one that actually lives the entire
lifetime of your program or not (or even if you want it to live that long, if
it could). Most of the time, the problem in the code is an attempt to create a
dangling reference or a mismatch of the available lifetimes, and the solution
is fixing those problems, not specifying the <code>'static</code> lifetime.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#generic-type-parameters-trait-bounds-and-lifetimes-together" id="generic-type-parameters-trait-bounds-and-lifetimes-together"><h3>Generic Type Parameters, Trait Bounds, and Lifetimes Together</h3></a>
<p>Let's briefly look at the syntax of specifying generic type parameters, trait
bounds, and lifetimes all in one function!</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
use std::fmt::Display;

fn longest_with_an_announcement&lt;'a, T&gt;(x: &amp;'a str, y: &amp;'a str, ann: T) -&gt; &amp;'a str
    where T: Display
{
    println!(&quot;Announcement! {}&quot;, ann);
    if x.len() &gt; y.len() {
        x
    } else {
        y
    }
}

#}</code></pre></pre>
<p>This is the <code>longest</code> function from Listing 10-21 that returns the longest of
two string slices, but with an extra argument named <code>ann</code>. The type of <code>ann</code> is
the generic type <code>T</code>, which may be filled in by any type that implements the
<code>Display</code> trait as specified by the <code>where</code> clause. This extra argument will be
printed out before the function compares the lengths of the string slices,
which is why the <code>Display</code> trait bound is necessary. Because lifetimes are a
type of generic, the declarations of both the lifetime parameter <code>'a</code> and the
generic type parameter <code>T</code> go in the same list within the angle brackets after
the function name.</p>
<a class="header" href="ch10-03-lifetime-syntax.html#summary" id="summary"><h2>Summary</h2></a>
<p>We covered a lot in this chapter! Now that you know about generic type
parameters, traits and trait bounds, and generic lifetime parameters, you're
ready to write code that isn't duplicated but can be used in many different
situations. Generic type parameters mean the code can be applied to different
types. Traits and trait bounds ensure that even though the types are generic,
those types will have the behavior the code needs. Relationships between the
lifetimes of references specified by lifetime annotations ensure that this
flexible code won't have any dangling references. And all of this happens at
compile time so that run-time performance isn't affected!</p>
<p>Believe it or not, there's even more to learn in these areas: Chapter 17 will
discuss trait objects, which are another way to use traits. Chapter 19 will be
covering more complex scenarios involving lifetime annotations. Chapter 20 will
get to some advanced type system features. Up next, though, let's talk about
how to write tests in Rust so that we can make sure our code using all these
features is working the way we want it to!</p>

                </div>

                <!-- Mobile navigation buttons -->
                
                    <a href="ch10-02-traits.html" class="mobile-nav-chapters previous">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="ch11-00-testing.html" class="mobile-nav-chapters next">
                        <i class="fa fa-angle-right"></i>
                    </a>
                

            </div>

            
                <a href="ch10-02-traits.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-left"></i>
                </a>
            

            
                <a href="ch11-00-testing.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-right"></i>
                </a>
            

        </div>


        <!-- Local fallback for Font Awesome -->
        <script>
            if ($(".fa").css("font-family") !== "FontAwesome") {
                $('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
            }
        </script>

        <!-- Livereload script (if served using the cli tool) -->
        

        <script src="highlight.js"></script>
        <script src="book.js"></script>
    </body>
</html>