Files
book/slices.html
T

356 lines
18 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"><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" class="active"><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>Slices</h1>
<p>So far, we’ve talked about types that have ownership, like <code>String</code>, and ones
that don’t, like <code>&amp;String</code>. There is a second kind of type which does not have
ownership: slices. Slices let you reference a contiguous sequence of elements
in a collection, rather than the whole collection itself.</p>
<p>Here’s a small programming problem: write a function which takes a string,
and returns the first word you find. If we don’t find a space in the string,
then the whole string is a word, so the whole thing should be returned.</p>
<p>Let’s think about the signature of this function:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;String) -&gt; ?
</code></pre>
<p>This function, <code>first_word</code>, takes a <code>&amp;String</code> as an argument. We don’t want
ownership, so this is fine. But what should we return? We don’t really have a
way to talk about <em>part</em> of a string. We could return the index of the end of
the word, though. Let’s try that:</p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; usize {
let bytes = s.as_bytes();
for (i, &amp;byte) in bytes.iter().enumerate() {
if byte == 32 {
return i;
}
}
s.len()
}
</code></pre>
<p>Let’s break that down a bit:</p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; usize {
// Since we need to go through the String element by element, and
// check if a value is a space, we will convert our String to an
// array of bytes, using the `.as_bytes()` method.
let bytes = s.as_bytes();
// We discussed using the iter() method with for in Chapter 3.7. Here,
// we’re adding another method: enumerate(). While iter() returns each
// element, enumerate() modifies the result of iter(), and returns a
// tuple instead. The first element of the tuple is the index, and the
// second element is a reference to the element itself. This is a bit
// nicer than calculating the index ourselves.
//
// Since it’s a tuple, we can use patterns, just like elsewhere in Rust.
// So we match against the tuple with i for the index, and &amp;byte for
// the byte itself.
for (i, &amp;byte) in bytes.iter().enumerate() {
// 32 is the value of a space in UTF-8
if byte == 32 {
// We found a space! Return this position.
return i;
}
}
// If we got here, we didn’t find a space, so this whole thing must be a
// word. So return the length.
s.len()
}
</code></pre>
<p>This works, but there’s a problem. We’re returning a <code>usize</code> on its own, but
it’s only a meaningful number in the context of the <code>&amp;String</code> itself. In other
words, because it’s a separate value from the <code>String</code>, there’s no guarantee
that it will still be valid in the future. Consider this:</p>
<pre><code class="language-rust"># fn first_word(s: &amp;String) -&gt; usize {
# let bytes = s.as_bytes();
#
# for (i, &amp;byte) in bytes.iter().enumerate() {
# if byte == 32 {
# return i;
# }
# }
#
# s.len()
# }
fn main() {
let mut s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s);
s.clear(); // This empties the String, making it equal to &quot;&quot;.
// word is now totally invalid! There’s no more word here.
}
</code></pre>
<p>This is bad! It’s even worse if we wanted to write a <code>second_word()</code>
function. Its signature would have to look like this:</p>
<pre><code class="language-rust,ignore">fn second_word(s: &amp;String) -&gt; (usize, usize) {
</code></pre>
<p>Now we’re tracking both a start <em>and</em> and ending index. Even more chances for
things to go wrong. We now have three unrelated variable bindings floating
around which need to be kept in sync.</p>
<p>Luckily, Rust has a solution to this probem: string slices.</p>
<h1>String slices</h1>
<p>A string slice looks like this:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello world&quot;);
let hello = &amp;s[0..5];
let world = &amp;s[5..9];
</code></pre>
<p>This looks just like taking a reference to the whole <code>String</code>, but with the
extra <code>[0..5]</code> bit. Instead of being a reference to the entire <code>String</code>,
it’s a reference to an internal position in the <code>String</code>, but it also keeps
track of the number of elements that it refers to as well. In other words,
it looks like this:</p>
<p>DIAGRAM GOES HERE of s, hello, and world</p>
<p>With Rust’s <code>..</code> syntax, if you want to start at zero, you can drop the zero.
In other words, these are equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let slice = &amp;s[0..2];
let slice = &amp;s[..2];
</code></pre>
<p>By the same token, if you want to go to the maximum value, which for slices is
the last element, you can drop the trailing number. In other words, these are
equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let len = s.len();
let slice = &amp;s[1..len];
let slice = &amp;s[1..];
</code></pre>
<p>With this in mind, let’s re-write <code>first_word()</code> to return a slice:</p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; &amp;str {
let bytes = s.as_bytes();
for (i, &amp;byte) in bytes.iter().enumerate() {
if byte == 32 {
return &amp;s[0..i];
}
}
&amp;s[..]
}
</code></pre>
<p>Now, we have a single value, the <code>&amp;str</code>. It contains both elements that we care
about: a reference to the starting point, and the number of elements.
This would also work for a <code>second_word()</code>:</p>
<pre><code class="language-rust,ignore">fn second_word(s: &amp;String) -&gt; &amp;str {
</code></pre>
<p>Same deal. We now have a straightforward API, that’s much harder to mess up.</p>
<p>But what about our error condition from before? Slices also fix that. Using
the slice version of <code>first_word()</code> will throw an error:</p>
<pre><code class="language-rust,ignore"># fn first_word(s: &amp;String) -&gt; &amp;str {
# let bytes = s.as_bytes();
#
# for (i, &amp;byte) in bytes.iter().enumerate() {
# if byte == 32 {
# return &amp;s[0..i];
# }
# }
#
# &amp;s[..]
# }
fn main() {
let mut s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s);
s.clear(); // Error!
}
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">17:6 error: cannot borrow `s` as mutable because it is also borrowed as
immutable [E0502]
s.clear(); // Error!
^
15:29 note: previous borrow of `s` occurs here; the immutable borrow prevents
subsequent moves or mutable borrows of `s` until the borrow ends
let word = first_word(&amp;s);
^
18:2 note: previous borrow ends here
fn main() {
}
^
</code></pre>
<p>Remember the borrowing rules? If we have an immutable reference to something,
we cannot also take a mutable reference. Since <code>clear()</code> needs to truncate the
<code>String</code>, it tries to take a mutable reference, which fails. Not only has Rust
made our API easier to use, but it’s also eliminated an entire class of errors
at compile time!</p>
<h3>String literals are slices</h3>
<p>Remember how we talked about string literals being stored inside of the binary
itself? Now that we know about slices, we can now properly understand string
literals.</p>
<pre><code class="language-rust">let s = &quot;Hello, world!&quot;;
</code></pre>
<p>The type of <code>s</code> here is <code>&amp;str</code>: It’s a slice, pointing to that specific point
of the binary. This is also why string literals are immutable; <code>&amp;str</code> is an
immutable reference.</p>
<h2>String slices as arguments</h2>
<p>Knowing that you can take slices of both literals and <code>String</code>s leads us to
one more improvement on <code>first_word()</code>, and that’s its signature:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;String) -&gt; &amp;str {
</code></pre>
<p>A more experienced Rustacean would write this one instead:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;str) -&gt; &amp;str {
</code></pre>
<p>Why is this? Well, we aren’t trying to modify <code>s</code> at all. And we can take
a string slice that’s the full length of a <code>String</code>, so we haven’t lost
the ability to talk about full <code>String</code>s. And additionally, we can take
string slices of string literals too, so this function is more useful, but
with no loss of functionality:</p>
<pre><code class="language-rust"># fn first_word(s: &amp;str) -&gt; &amp;str {
# let bytes = s.as_bytes();
#
# for (i, &amp;byte) in bytes.iter().enumerate() {
# if byte == 32 {
# return &amp;s[0..i];
# }
# }
#
# &amp;s[..]
# }
fn main() {
let s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s[..]);
let s = &quot;hello world&quot;;
let word = first_word(&amp;s[..]);
let word = first_word(s); // since literals are &amp;strs, this works too!
}
</code></pre>
<h1>Other slices</h1>
<p>String slices, as you might imagine, are specific to strings. But there’s a more
general slice type, too. Consider arrays:</p>
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
</code></pre>
<p>Just like we may want to refer to a part of a string, we may want to refer to
part of an array:</p>
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
let slice = &amp;a[1..3];
</code></pre>
<p>This slice has the type <code>&amp;[i32]</code>. It works the exact same way as string slices
do, with a reference to the first element, and a length. You’ll use this kind
of slice for all sorts of other collections. We’ll discuss these other slices
in detail when we talk about vectors, in Chapter 9.1.</p>
</div>
<!-- Mobile navigation buttons -->
<a href="references-and-borrowing.html" class="mobile-nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="structs.html" class="mobile-nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<a href="references-and-borrowing.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="structs.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>