<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <title>References and Borrowing</title> <link rel="stylesheet" type="text/css" href="../rust.css"> <link rel="shortcut icon" href="https://www.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <div id="versioninfo"> <img src="https://www.rust-lang.org/logos/rust-logo-32x32-blk.png" width="32" height="32" alt="Rust logo"><br> <span class="white-sticker"><a href="https://www.rust-lang.org">Rust</a> 1.27.1</span><br> <a href="https://github.com/rust-lang/rust/commit/" class="hash white-sticker"></a> </div> <h1 class="title">References and Borrowing</h1> <p><small>There is a new edition of the book and this is an old link.</small></p> <blockquote> <p>A reference <em>refers</em> to a value but does not own it. Because it does not own it, the value it points to will not be dropped when the reference goes out of scope.</p> </blockquote> <pre class="rust rust-example-rendered"> <span class="kw">fn</span> <span class="ident">calculate_length</span>(<span class="ident">s</span>: <span class="kw-2">&</span><span class="ident">String</span>) <span class="op">-></span> <span class="ident">usize</span> { <span class="comment">// s is a reference to a String</span> <span class="ident">s</span>.<span class="ident">len</span>() } <span class="comment">// Here, s goes out of scope. But because it does not have ownership of what</span> <span class="comment">// it refers to, nothing happens.</span><a class="test-arrow" target="_blank" href="https://play.rust-lang.org/?code=%23!%5Ballow(unused)%5D%0Afn%20main()%20%7B%0Afn%20calculate_length(s%3A%20%26String)%20-%3E%20usize%20%7B%20%2F%2F%20s%20is%20a%20reference%20to%20a%20String%0A%20%20%20%20s.len()%0A%7D%20%2F%2F%20Here%2C%20s%20goes%20out%20of%20scope.%20But%20because%20it%20does%20not%20have%20ownership%20of%20what%0A%20%20%2F%2F%20it%20refers%20to%2C%20nothing%20happens.%0A%7D">Run</a></pre> <hr /> <p>Here are the relevant sections in the new and old books:</p> <ul> <li><strong><a href="second-edition/ch04-02-references-and-borrowing.html">In the second edition: Ch 4.02 — References and Borrowing</a></strong></li> <li><small><a href="first-edition/references-and-borrowing.html">In the first edition: Ch 3.9 — References and Borrowing</a></small></li> </ul> <footer><p> Copyright © 2011 The Rust Project Developers. Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a> or the <a href="https://opensource.org/licenses/MIT">MIT license</a>, at your option. </p><p> This file may not be copied, modified, or distributed except according to those terms. </p></footer> </body> </html>