Files
book/ownership.html
T

482 lines
28 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>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='http://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="http://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">
<!-- 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="http://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>
<!-- 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="introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="hello-world.html"><strong>1.2.</strong> Hello, World!</a></li><li><a href="design.html"><strong>1.3.</strong> The Design of Rust</a></li></ul></li><li><strong>2.</strong> Tutorial</li><li><a href="up-and-running.html"><strong>3.</strong> Up and Running</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="scalar-types.html"><strong>3.3.</strong> Scalar Types</a></li><li><a href="compound-types.html"><strong>3.4.</strong> Compound Types</a></li><li><a href="comments.html"><strong>3.5.</strong> Comments</a></li><li><a href="if.html"><strong>3.6.</strong> Control flow with <code>if</code></a></li><li><a href="loops.html"><strong>3.7.</strong> Loops</a></li></ul></li><li><a href="understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ownership.html" class="active"><strong>4.1.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>4.2.</strong> References &amp; Borrowing</a></li><li><a href="slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="structs.html"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><strong>5.1.</strong> Method Syntax</li><li><strong>5.2.</strong> Generics</li><li><strong>5.3.</strong> Advanced</li></ul></li><li><strong>6.</strong> Enums</li><li><ul class="section"><li><strong>6.1.</strong> Match</li><li><strong>6.2.</strong> Patterns</li><li><strong>6.3.</strong> Option</li><li><strong>6.4.</strong> if let</li></ul></li><li><strong>7.</strong> Crates &amp; Modules</li><li><strong>8.</strong> Error Handling</li><li><strong>9.</strong> Basic Collections</li><li><ul class="section"><li><strong>9.1.</strong> Vectors</li><li><strong>9.2.</strong> Strings</li><li><strong>9.3.</strong> <code>HashMap&lt;K, V&gt;</code></li></ul></li><li><strong>10.</strong> Lifetimes</li><li><strong>11.</strong> Traits</li><li><strong>12.</strong> Closures</li><li><strong>13.</strong> Iterators</li><li><strong>14.</strong> I/O</li><li><ul class="section"><li><strong>14.1.</strong> <code>Read</code> &amp; <code>Write</code></li><li><strong>14.2.</strong> <code>std::fs</code></li><li><strong>14.3.</strong> <code>std::path</code></li><li><strong>14.4.</strong> <code>std::env</code></li></ul></li><li><strong>15.</strong> Testing</li><li><strong>16.</strong> Smart Pointers</li><li><ul class="section"><li><strong>16.1.</strong> <code>Deref</code></li><li><strong>16.2.</strong> <code>Deref</code> coercions</li><li><strong>16.3.</strong> <code>Box&lt;T&gt;</code></li><li><strong>16.4.</strong> <code>Rc&lt;T&gt;</code></li></ul></li><li><strong>17.</strong> Concurrency</li><li><ul class="section"><li><strong>17.1.</strong> Threads</li><li><strong>17.2.</strong> <code>Send</code> &amp; <code>Sync</code></li><li><strong>17.3.</strong> <code>Arc&lt;T&gt;</code></li><li><strong>17.4.</strong> <code>Mutex&lt;T&gt;</code></li><li><strong>17.5.</strong> <code>Channels</code></li></ul></li><li><strong>18.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>18.1.</strong> Raw Pointers</li><li><strong>18.2.</strong> transmute</li></ul></li><li><strong>19.</strong> FFI</li><li><ul class="section"><li><strong>19.1.</strong> Conditional Compilation</li><li><strong>19.2.</strong> Bindings to C</li><li><strong>19.3.</strong> Using Rust from Other Languages</li><li><strong>19.4.</strong> <code>static</code></li></ul></li><li><strong>20.</strong> Cargo</li><li><ul class="section"><li><strong>20.1.</strong> Crates.io</li></ul></li><li><strong>21.</strong> Advanced Type System Features</li><li><ul class="section"><li><strong>21.1.</strong> Associated Types</li><li><strong>21.2.</strong> Trait Objects</li><li><strong>21.3.</strong> UFCS</li><li><strong>21.4.</strong> Coherence</li></ul></li><li><strong>22.</strong> Interior mutability</li><li><ul class="section"><li><strong>22.1.</strong> <code>Cell&lt;T&gt;</code></li><li><strong>22.2.</strong> <code>RefCell&lt;T&gt;</code></li></ul></li><li><strong>23.</strong> Macros</li><li><strong>24.</strong> Nightly Rust</li></ul>
</div>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<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">
<h1>Ownership</h1>
<p>Rust’s central feature is called ‘ownership’. It is a feature that is
straightforward to explain, but has deep implications for the rest of the
language.</p>
<p>Rust is committed to both safety and speed. One of the key tools for balancing
between them is “zero-cost abstractions”: the various abstractions in Rust do
not pose a global performance penalty. The ownership system is a prime example
of a zero-cost abstraction. All of the analysis we’ll talk about in this guide
is done at compile time. 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
Rustaceans 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 can happen because the programmer isn’t used to thinking
carefully about ownership, or is thinking about it differently from the way
that Rust does. You probably will experience something similar 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. Keep at it!</p>
<p>This chapter will give you a foundation for understanding the rest of the
language. To do so, we’re going to learn through examples, focusing on a very
common data structure: strings.</p>
<h2>Variable binding scope</h2>
<p>Let’s take a step back and look at the very basics again. Now that we’re past
basic syntax, we won’t include all of the <code>fn main() {</code> stuff in examples, so
if you’re following along, you will have to put them inside of a <code>main()</code>
function. This lets our examples be a bit more concise, letting us focus on the
actual details, rather than boilerplate.</p>
<p>Anyway, here it is:</p>
<pre><code class="language-rust">let s = &quot;hello&quot;;
</code></pre>
<p>This variable binding refers to a string literal. It’s valid from the point at
which it’s declared, until the end of the current <em>scope</em>. That is:</p>
<pre><code class="language-rust">{ // s is not valid here, it’s not yet in scope
let s = &quot;hello&quot;; // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
</code></pre>
<p>In other words, there are two important points in time here:</p>
<ul>
<li>When <code>s</code> comes ‘into scope’, it is valid.</li>
<li>It remains so until it ‘goes out of scope’.</li>
</ul>
<p>At this point, things are similar to other programming languages. Let’s build
on top of this understanding by introducing a new type: <code>String</code>.</p>
<h2>Strings</h2>
<p>String literals are convenient, but they aren’t the only way that you use strings.
For one thing, they’re immutable. For another, not every string is literal:
what about taking user input and storing it in a string?</p>
<p>For this, Rust has a second string type, <code>String</code>. You can create a <code>String</code> from
a string literal using the <code>from</code> function:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
</code></pre>
<p>We haven’t seen the double colon (<code>::</code>) syntax yet. It is a kind of scope
operator, allowing us to namespace this particular <code>from()</code> function under the
<code>String</code> type itself, rather than using some sort of name like <code>string_from()</code>.
We’ll discuss this syntax more in the “Method Syntax” and “Modules” chapters.</p>
<p>This kind of string can be mutated:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;hello&quot;);
s.push_str(&quot;, world!&quot;);
</code></pre>
<h2>Memory and allocation</h2>
<p>So, what’s the difference here? Why can <code>String</code> be mutated, but literals
cannot? The difference comes down to how these two types deal with memory.</p>
<p>In the case of a string literal, because we know the contents of the string at
compile time, we can hard-code the text of the string directly into the final
executable. This means that string literals are quite fast and efficient. But
these properties only come from its immutability; we can’t put an
arbitrary-sized blob of memory into the binary for each string!</p>
<p>With <code>String</code>, to support a mutable, growable string, we need to allocate an
unknown amount of memory to hold the contents. This means two things:</p>
<ol>
<li>The memory must be requested from the operating system at runtime.</li>
<li>We need a way of giving this memory back to the operating system when we’re
done with our <code>String</code>.</li>
</ol>
<p>That first part is done by us: when we call <code>String::from()</code>, its
implementation requests the memory it needs. This is pretty much universal in
programming languages.</p>
<p>The second case, however, is different. In languages with a garbage collector
(‘GC’), the GC handles that second case, and we, as the programmer, don’t need
to think about it. Without GC, it’s the programmer’s responsibility to identify
when memory is no longer being used, and explicitly return it, just as it was
requested. Doing this correctly has historically been a difficult problem. If
we forget, we will waste memory. If we do it too early, we will have an invalid
variable. If we do it twice, that’s a bug too. We need to pair exactly one
<code>allocate()</code> with exactly one <code>free()</code>.</p>
<p>Rust takes a different path. Remember our example? Here’s a version with
<code>String</code>:</p>
<pre><code class="language-rust">{
let s = String::from(&quot;hello&quot;); // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
</code></pre>
<p>We have a natural point at which we can return the memory our <code>String</code> needs back
to the operating system: when it goes out of scope! When a variable goes out of
scope, a special function is called. This function is called <code>drop()</code>, and it
is where the author of <code>String</code> can put the code to return the memory.</p>
<blockquote>
<p>Aside: This pattern is sometimes called “Resource Aquisition Is
Initialization” in C++, or “RAII” for short. While they are very similar,
Rust’s take on this concept has a number of differences, and so we don’t tend
to use the same term. If you’re familliar with this idea, keep in mind that it
is <em>roughly</em> similar in Rust, but not identical.</p>
</blockquote>
<p>This pattern has a profound impact on the way that Rust code is written. It may
seem obvious right now, but things can get tricky in more advanced situations!
Let’s go over the first one of those right now.</p>
<h2>Move</h2>
<p>What would you expect this code to do?</p>
<pre><code class="language-rust">let x = 5;
let y = x;
</code></pre>
<p>You might say “Make a copy of <code>5</code>.” That’d be correct! We now have two
bindings, <code>x</code> and <code>y</code>, and both equal <code>5</code>.</p>
<p>Now let’s look at <code>String</code>. What would you expect this code to do?</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = s1;
</code></pre>
<p>You might say “copy the <code>String</code>!” This is both correct and incorrect at the
same time. It does a <em>shallow</em> copy of the <code>String</code>. What’s that mean? Well,
let’s take a look at what <code>String</code> looks like under the covers:</p>
<p><img alt="string" src="img/foo1.png" class="center" style="width: 50%;" /></p>
<p>A <code>String</code> is made up of three parts: a pointer to the memory that holds the
contents of the string, a length, and a capacity. The length is how much memory
the <code>String</code> is currently using. The capacity is the total amount of memory the
<code>String</code> has gotten from the operating system. The difference between length
and capacity matters, but not in this context, so don’t worry about it too much
if it doesn’t make sense, and just ignore the capacity.</p>
<blockquote>
<p>We’ve talked about two kinds of composite types: arrays and tuples. <code>String</code>
is a third type: a <code>struct</code>, which we will cover the details of in the next
chapter of the book. For now, thinking about <code>String</code> as a tuple is close
enough.</p>
</blockquote>
<p>When we assign <code>s1</code> to <code>s2</code>, the <code>String</code> itself is copied. But not all kinds
of copying are the same. Many people draw distinctions between ‘shallow
copying’ and ‘deep copying’. We don’t use these terms in Rust. We instead say
that something is ‘moved’ or ‘cloned’. Assignment in Rust causes a ‘move’. In
other words, it looks like this:</p>
<p><img alt="s1 and s2" src="img/foo2.png" class="center" style="width: 50%;" /></p>
<p><em>Not</em> this:</p>
<p><img alt="s1 and s2 to two places" src="img/foo4.png" class="center" style="width: 50%;" /></p>
<p>When moving, Rust makes a copy of the data structure itself, the contents of
<code>s1</code> are copied, but if <code>s1</code> contains a reference, like it does in this case,
Rust will not copy the things that those references refer to.</p>
<p>There’s a problem here! Both <code>data</code> pointers are pointing to the same place.
Why is this a problem? Well, when <code>s2</code> goes out of scope, it will free the
memory that <code>data</code> points to. And then <code>s1</code> goes out of scope, and it will
<em>also</em> try to free the memory that <code>data</code> points to! That’s bad.</p>
<p>So what’s the solution? Here, we stand at a crossroads. There are a few
options. One would be to declare that assignment will also copy out any data.
This works, but is inefficient: what if our <code>String</code> contained a novel? Also,
it only works for memory. What if, instead of a <code>String</code>, we had a
<code>TcpConnection</code>? Opening and closing a network connection is very similar to
allocating and freeing memory. The solution that we could use there is to allow
the programmer to hook into the assignment, similar to <code>drop()</code>, and write code
fix things up. That would work, but now, an <code>=</code> can run arbitrary code. That’s
also not good, and it doesn’t solve our efficiency concerns either.</p>
<p>Let’s take a step back: the root of the problem is that <code>s1</code> and <code>s2</code> both
think that they have control of the memory, and therefore needs to free it.
Instead of trying to copy the allocated memory, we could say that <code>s1</code> is no
longer valid, and therefore, doesn’t need to free anything. This is in fact the
choice that Rust makes. Check it out what happens when you try to use <code>s1</code>
after <code>s2</code> is created:</p>
<pre><code class="language-rust,ignore">let s1 = String::from(&quot;hello&quot;);
let s2 = s1;
println!(&quot;{}&quot;, s1);
</code></pre>
<p>You’ll get an error like this:</p>
<pre><code class="language-text">5:22 error: use of moved value: `s1` [E0382]
println!(&quot;{}&quot;, s1);
^~
5:24 note: in this expansion of println! (defined in &lt;std macros&gt;)
3:11 note: `s1` moved here because it has type `collections::string::String`, which is moved by default
let s2 = s1;
^~
</code></pre>
<p>We say that <code>s1</code> was <em>moved</em> into <code>s2</code>. When a value moves, its data is copied,
but the original variable binding is no longer usable. That solves our problem:</p>
<p><img alt="s1 and s2 to the same place" src="img/foo3.png" class="center" style="width: 50%;" /></p>
<p>With only <code>s2</code> valid, when it goes out of scope, it will free the memory, and we’re done!</p>
<h2>Ownership Rules</h2>
<p>This leads us to the Ownership Rules:</p>
<blockquote>
<ol>
<li>Each value in Rust has a variable binding that’s called it’s ‘owner’.</li>
<li>There can only be one owner at a time.</li>
<li>When the owner goes out of scope, the value will be <code>drop()</code>ped.</li>
</ol>
</blockquote>
<p>Furthermore, there’s a design choice that’s implied by this: Rust will never
automatically create ‘deep’ copies of your data. Any automatic copying must be
inexpensive.</p>
<h2>Clone</h2>
<p>But what if we <em>do</em> want to deeply copy the <code>String</code>’s data, and not just the
<code>String</code> itself? There’s a common method for that: <code>clone()</code>. Here’s an example
of <code>clone()</code> in action:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = s1.clone();
println!(&quot;{}&quot;, s1);
</code></pre>
<p>This will work just fine. Remember our diagram from before? In this case,
it <em>is</em> doing this:</p>
<p><img alt="s1 and s2 to two places" src="img/foo4.png" class="center" style="width: 50%;" /></p>
<p>When you see a call to <code>clone()</code>, you know that some arbitrary code is being
executed, which may be expensive. It’s a visual indicator that something
different is going on here.</p>
<h2>Copy</h2>
<p>There’s one last wrinkle that we haven’t talked about yet. This code works:</p>
<pre><code class="language-rust">let x = 5;
let y = x;
println!(&quot;{}&quot;, x);
</code></pre>
<p>But why? We don’t have a call to <code>clone()</code>. Why didn’t <code>x</code> get moved into <code>y</code>?</p>
<p>For types that do not have any kind of complex storage requirements, like
integers, typing <code>clone()</code> is busy work. There’s no reason we would ever want
to prevent <code>x</code> from being valid here, as there’s no situation in which it’s
incorrect. In other words, there’s no difference between deep and shallow
copying here, so calling <code>clone()</code> wouldn’t do anything differently from the
usual shallow copying.</p>
<p>Rust has a special annotation that you can place on types, called <code>Copy</code>. If
a type is <code>Copy</code>, an older binding is still usable after assignment. Integers
are an example of such a type; most of the primitive types are <code>Copy</code>.</p>
<p>While we haven’t talked about how to mark a type as <code>Copy</code> yet, you might ask
yourself “what happens if we made <code>String</code> <code>Copy</code>?” The answer is, you cannot.
Remember <code>drop()</code>? Rust will not let you make something <code>Copy</code> if it has
implemented <code>drop()</code>. If you need to do something special when the value goes
out of scope, being <code>Copy</code> will be an error.</p>
<p>So what types are <code>Copy</code>? You can check the documentation for the given type to
be sure, but as a rule of thumb, any group of simple scalar values can be
Copy, but nothing that requires allocation or is some form of resource is <code>Copy</code>.
And you can’t get it wrong: the compiler will throw an error if you try to use
a type that moves incorrectly, as we saw above.</p>
<p>Here’s some types that you’ve seen so far that are <code>Copy</code>:</p>
<ul>
<li>All of the integer types, like <code>u32</code>.</li>
<li>The booleans, <code>true</code> and <code>false</code>.</li>
<li>All of the floating point types, like <code>f64</code>.</li>
<li>Tuples, but only if they contain types which are also <code>Copy</code>. <code>(i32, i32)</code>
is <code>Copy</code>, but <code>(i32, String)</code> is not!</li>
</ul>
<h2>Ownership and functions</h2>
<p>Passing a value to a function has similar semantics as assigning it:</p>
<pre><code class="language-rust">fn main() {
let s = String::from(&quot;hello&quot;);
takes_ownership(s);
let x = 5;
makes_copy(x);
}
fn takes_ownership(some_string: String) {
println!(&quot;{}&quot;, some_string);
}
fn makes_copy(some_integer: i32) {
println!(&quot;{}&quot;, some_integer);
}
</code></pre>
<p>Passing a binding to a function will move or copy, just like assignment. Here’s
the same example, but with some annotations showing where things go into and
out of scope:</p>
<pre><code class="language-rust">fn main() {
let s = String::from(&quot;hello&quot;); // s goes into scope.
takes_ownership(s); // s moves into the function...
// ... and so is no longer valid here.
let x = 5; // x goes into scope.
makes_copy(x); // x would move into the function,
// but i32 is Copy, so it’s okay to still
// use x afterward.
} // Here, x goes out of scope, then s. But since s was moved, nothing special
// happens.
fn takes_ownership(some_string: String) { // some_string comes into scope.
println!(&quot;{}&quot;, some_string);
} // Here, some_string goes out of scope and `drop()` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) { // some_integer comes into scope.
println!(&quot;{}&quot;, some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
</code></pre>
<p>Remember: If we tried to use <code>s</code> after the call to <code>takes_ownership()</code>, Rust
would throw a compile-time error! These static checks protect us from mistakes.</p>
<p>Returning values can also transfer ownership:</p>
<pre><code class="language-rust">fn main() {
let s1 = gives_ownership();
let s2 = String::from(&quot;hello&quot;);
let s3 = takes_and_gives_back(s2);
}
fn gives_ownership() -&gt; String {
let some_string = String::from(&quot;hello&quot;);
some_string
}
fn takes_and_gives_back(a_string: String) -&gt; String {
a_string
}
</code></pre>
<p>With simililar annotations:</p>
<pre><code class="language-rust">fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1.
let s2 = String::from(&quot;hello&quot;); // s2 comes into scope
let s3 = takes_and_gives_back(s2); // s2 is moved into
// takes_and_gives_back, which also
// moves its return value into s3.
} // Here, s3 goes out of scope, and is dropped. s2 goes out of scope, but was
// moved, so nothing happens. s1 goes out of scope, and is dropped.
fn gives_ownership() -&gt; String { // gives_ownership will move its
// return value into the function
// that calls it.
let some_string = String::from(&quot;hello&quot;); // some_string comes into scope.
some_string // some_string is returned, and
// moves out to the calling
// function.
}
// takes_and_gives_back will both take a String and return one
fn takes_and_gives_back(a_string: String) -&gt; String { // a_string comes into scope
a_string // a_string is returned, and moves out to the calling function
}
</code></pre>
<p>It’s the same pattern, every time: assigning something moves it, and when an
owner goes out of scope, if it hasn’t been moved, it will <code>drop()</code>.</p>
<p>This might seem a bit tedious, and it is. What if I want to let a function use
a value, but not take ownership? It’s quite annoying that anything I pass in
also needs passed back. Look at this function:</p>
<pre><code class="language-rust">fn main() {
let s1 = String::from(&quot;hello&quot;);
let (s2, len) = calculate_length(s1);
println!(&quot;The length of '{}' is {}.&quot;, s2, len);
}
fn calculate_length(s: String) -&gt; (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
</code></pre>
<p>This is too much ceremony: we have to use a tuple to give back the <code>String</code> as
well as the length. It’s a lot of work for a pattern that should be common.</p>
<p>Luckily for us, Rust has such a feature, and it’s what the next section is about.</p>
</div>
<!-- Mobile navigation buttons -->
<a href="understanding-ownership.html" class="mobile-nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="references-and-borrowing.html" class="mobile-nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<a href="understanding-ownership.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="references-and-borrowing.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>
<script src="highlight.js"></script>
<script src="book.js"></script>
</body>
</html>