feat: added cleanscript

This commit is contained in:
2026-06-22 21:27:36 +05:30
parent dbddc0ce2d
commit 4581eea409
309 changed files with 14551 additions and 46035 deletions

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Understanding Ownership</title>
</head>
<body>
<h1 id="understanding-ownership"><a class="header" href="#understanding-ownership">Understanding Ownership</a></h1>
<p>Ownership is Rusts most unique feature and has deep implications for the rest
of the language. It enables Rust to make memory safety guarantees without
needing a garbage collector, so its important to understand how ownership
works. In this chapter, well talk about ownership as well as several related
features: borrowing, slices, and how Rust lays data out in memory.</p>
</body>
</html>

View File

@@ -0,0 +1,527 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>What is Ownership?</title>
</head>
<body>
<h2 id="what-is-ownership"><a class="header" href="#what-is-ownership">What Is Ownership?</a></h2>
<p><em>Ownership</em> is a set of rules that govern how a Rust program manages memory.
All programs have to manage the way they use a computers memory while running.
Some languages have garbage collection that regularly looks for no-longer-used
memory as the program runs; in other languages, the programmer must explicitly
allocate and free the memory. Rust uses a third approach: Memory is managed
through a system of ownership with a set of rules that the compiler checks. If
any of the rules are violated, the program wont compile. None of the features
of ownership will slow down your program while its running.</p>
<p>Because ownership is a new concept for many programmers, it does take some time
to get used to. The good news is that the more experienced you become with Rust
and the rules of the ownership system, the easier youll find it to naturally
develop code that is safe and efficient. Keep at it!</p>
<p>When you understand ownership, youll have a solid foundation for understanding
the features that make Rust unique. In this chapter, youll learn ownership by
working through some examples that focus on a very common data structure:
strings.</p>
<section class="note" aria-role="note">
<h3 id="the-stack-and-the-heap"><a class="header" href="#the-stack-and-the-heap">The Stack and the Heap</a></h3>
<p>Many programming languages dont require you to think about the stack and the
heap very often. But in a systems programming language like Rust, whether a
value is on the stack or the heap affects how the language behaves and why
you have to make certain decisions. Parts of ownership will be described in
relation to the stack and the heap later in this chapter, so here is a brief
explanation in preparation.</p>
<p>Both the stack and the heap are parts of memory available to your code to use
at runtime, but they are structured in different ways. The stack stores
values in the order it gets them and removes the values in the opposite
order. This is referred to as <em>last in, first out (LIFO)</em>. Think of a stack of
plates: When you add more plates, you put them on top of the pile, and when
you need a plate, you take one off the top. Adding or removing plates from
the middle or bottom wouldnt work as well! Adding data is called <em>pushing
onto the stack</em>, and removing data is called <em>popping off the stack</em>. All
data stored on the stack must have a known, fixed size. Data with an unknown
size at compile time or a size that might change must be stored on the heap
instead.</p>
<p>The heap is less organized: When you put data on the heap, you request a
certain amount of space. The memory allocator finds an empty spot in the heap
that is big enough, marks it as being in use, and returns a <em>pointer</em>, which
is the address of that location. This process is called <em>allocating on the
heap</em> and is sometimes abbreviated as just <em>allocating</em> (pushing values onto
the stack is not considered allocating). Because the pointer to the heap is a
known, fixed size, you can store the pointer on the stack, but when you want
the actual data, you must follow the pointer. Think of being seated at a
restaurant. When you enter, you state the number of people in your group, and
the host finds an empty table that fits everyone and leads you there. If
someone in your group comes late, they can ask where youve been seated to
find you.</p>
<p>Pushing to the stack is faster than allocating on the heap because the
allocator never has to search for a place to store new data; that location is
always at the top of the stack. Comparatively, allocating space on the heap
requires more work because the allocator must first find a big enough space
to hold the data and then perform bookkeeping to prepare for the next
allocation.</p>
<p>Accessing data in the heap is generally slower than accessing data on the
stack because you have to follow a pointer to get there. Contemporary
processors are faster if they jump around less in memory. Continuing the
analogy, consider a server at a restaurant taking orders from many tables.
Its most efficient to get all the orders at one table before moving on to
the next table. Taking an order from table A, then an order from table B,
then one from A again, and then one from B again would be a much slower
process. By the same token, a processor can usually do its job better if it
works on data thats close to other data (as it is on the stack) rather than
farther away (as it can be on the heap).</p>
<p>When your code calls a function, the values passed into the function
(including, potentially, pointers to data on the heap) and the functions
local variables get pushed onto the stack. When the function is over, those
values get popped off the stack.</p>
<p>Keeping track of what parts of code are using what data on the heap,
minimizing the amount of duplicate data on the heap, and cleaning up unused
data on the heap so that you dont run out of space are all problems that
ownership addresses. Once you understand ownership, you wont need to think
about the stack and the heap very often. But knowing that the main purpose of
ownership is to manage heap data can help explain why it works the way it
does.</p>
</section>
<h3 id="ownership-rules"><a class="header" href="#ownership-rules">Ownership Rules</a></h3>
<p>First, lets take a look at the ownership rules. Keep these rules in mind as we
work through the examples that illustrate them:</p>
<ul>
<li>Each value in Rust has an <em>owner</em>.</li>
<li>There can only be one owner at a time.</li>
<li>When the owner goes out of scope, the value will be dropped.</li>
</ul>
<h3 id="variable-scope"><a class="header" href="#variable-scope">Variable Scope</a></h3>
<p>Now that were past basic Rust syntax, we wont include all the <code>fn main() {</code>
code in the examples, so if youre following along, make sure to put the
following examples inside a <code>main</code> function manually. As a result, our examples
will be a bit more concise, letting us focus on the actual details rather than
boilerplate code.</p>
<p>As a first example of ownership, well look at the scope of some variables. A
<em>scope</em> is the range within a program for which an item is valid. Take the
following variable:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = "hello";
<span class="boring">}</span></code></pre>
<p>The variable <code>s</code> refers to a string literal, where the value of the string is
hardcoded into the text of our program. The variable is valid from the point at
which its declared until the end of the current scope. Listing 4-1 shows a
program with comments annotating where the variable <code>s</code> would be valid.</p>
<figure class="listing" id="listing-4-1">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> { // s is not valid here, since it's not yet declared
let s = "hello"; // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-4-1">Listing 4-1</a>: A variable and the scope in which it is valid</figcaption>
</figure>
<p>In other words, there are two important points in time here:</p>
<ul>
<li>When <code>s</code> comes <em>into</em> scope, it is valid.</li>
<li>It remains valid until it goes <em>out of</em> scope.</li>
</ul>
<p>At this point, the relationship between scopes and when variables are valid is
similar to that in other programming languages. Now well build on top of this
understanding by introducing the <code>String</code> type.</p>
<h3 id="the-string-type"><a class="header" href="#the-string-type">The <code>String</code> Type</a></h3>
<p>To illustrate the rules of ownership, we need a data type that is more complex
than those we covered in the <a href="../ch03/ch03-02-data-types.html#data-types">“Data Types”</a><!-- ignore --> section
of Chapter 3. The types covered previously are of a known size, can be stored
on the stack and popped off the stack when their scope is over, and can be
quickly and trivially copied to make a new, independent instance if another
part of code needs to use the same value in a different scope. But we want to
look at data that is stored on the heap and explore how Rust knows when to
clean up that data, and the <code>String</code> type is a great example.</p>
<p>Well concentrate on the parts of <code>String</code> that relate to ownership. These
aspects also apply to other complex data types, whether they are provided by
the standard library or created by you. Well discuss non-ownership aspects of
<code>String</code> in <a href="../ch08/ch08-02-strings.html">Chapter 8</a><!-- ignore -->.</p>
<p>Weve already seen string literals, where a string value is hardcoded into our
program. String literals are convenient, but they arent suitable for every
situation in which we may want to use text. One reason is that theyre
immutable. Another is that not every string value can be known when we write
our code: For example, what if we want to take user input and store it? It is
for these situations that Rust has the <code>String</code> type. This type manages
data allocated on the heap and as such is able to store an amount of text that
is unknown to us at compile time. You can create a <code>String</code> from a string
literal using the <code>from</code> function, like so:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = String::from("hello");
<span class="boring">}</span></code></pre>
<p>The double colon <code>::</code> operator allows us to namespace this particular <code>from</code>
function under the <code>String</code> type rather than using some sort of name like
<code>string_from</code>. Well discuss this syntax more in the <a href="../ch05/ch05-03-method-syntax.html#methods">“Methods”</a><!--
ignore --> section of Chapter 5, and when we talk about namespacing with
modules in <a href="../ch07/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html">“Paths for Referring to an Item in the Module
Tree”</a><!-- ignore --> in Chapter 7.</p>
<p>This kind of string <em>can</em> be mutated:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
s.push_str(", world!"); // push_str() appends a literal to a String
println!("{s}"); // this will print `hello, world!`
<span class="boring">}</span></code></pre>
<p>So, whats the difference here? Why can <code>String</code> be mutated but literals
cannot? The difference is in how these two types deal with memory.</p>
<h3 id="memory-and-allocation"><a class="header" href="#memory-and-allocation">Memory and Allocation</a></h3>
<p>In the case of a string literal, we know the contents at compile time, so the
text is hardcoded directly into the final executable. This is why string
literals are fast and efficient. But these properties only come from the string
literals immutability. Unfortunately, we cant put a blob of memory into the
binary for each piece of text whose size is unknown at compile time and whose
size might change while running the program.</p>
<p>With the <code>String</code> type, in order to support a mutable, growable piece of text,
we need to allocate an amount of memory on the heap, unknown at compile time,
to hold the contents. This means:</p>
<ul>
<li>The memory must be requested from the memory allocator at runtime.</li>
<li>We need a way of returning this memory to the allocator when were done with
our <code>String</code>.</li>
</ul>
<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>However, the second part is different. In languages with a <em>garbage collector
(GC)</em>, the GC keeps track of and cleans up memory that isnt being used
anymore, and we dont need to think about it. In most languages without a GC,
its our responsibility to identify when memory is no longer being used and to
call code to explicitly free it, just as we did to request it. Doing this
correctly has historically been a difficult programming problem. If we forget,
well waste memory. If we do it too early, well have an invalid variable. If
we do it twice, thats 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: The memory is automatically returned once the
variable that owns it goes out of scope. Heres a version of our scope example
from Listing 4-1 using a <code>String</code> instead of a string literal:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> {
let s = String::from("hello"); // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no
// longer valid
<span class="boring">}</span></code></pre>
<p>There is a natural point at which we can return the memory our <code>String</code> needs
to the allocator: when <code>s</code> goes out of scope. When a variable goes out of
scope, Rust calls a special function for us. This function is called
<code>drop</code>, and its where the author of <code>String</code> can put
the code to return the memory. Rust calls <code>drop</code> automatically at the closing
curly bracket.</p>
<section class="note" aria-role="note">
<p>Note: In C++, this pattern of deallocating resources at the end of an items
lifetime is sometimes called <em>Resource Acquisition Is Initialization (RAII)</em>.
The <code>drop</code> function in Rust will be familiar to you if youve used RAII
patterns.</p>
</section>
<p>This pattern has a profound impact on the way Rust code is written. It may seem
simple right now, but the behavior of code can be unexpected in more
complicated situations when we want to have multiple variables use the data
weve allocated on the heap. Lets explore some of those situations now.</p>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="ways-variables-and-data-interact-move"></a></p>
<h4 id="variables-and-data-interacting-with-move"><a class="header" href="#variables-and-data-interacting-with-move">Variables and Data Interacting with Move</a></h4>
<p>Multiple variables can interact with the same data in different ways in Rust.
Listing 4-2 shows an example using an integer.</p>
<figure class="listing" id="listing-4-2">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let x = 5;
let y = x;
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-4-2">Listing 4-2</a>: Assigning the integer value of variable <code>x</code> to <code>y</code></figcaption>
</figure>
<p>We can probably guess what this is doing: “Bind the value <code>5</code> to <code>x</code>; then, make
a copy of the value in <code>x</code> and bind it to <code>y</code>.” We now have two variables, <code>x</code>
and <code>y</code>, and both equal <code>5</code>. This is indeed what is happening, because integers
are simple values with a known, fixed size, and these two <code>5</code> values are pushed
onto the stack.</p>
<p>Now lets look at the <code>String</code> version:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let s1 = String::from("hello");
let s2 = s1;
<span class="boring">}</span></code></pre>
<p>This looks very similar, so we might assume that the way it works would be the
same: That is, the second line would make a copy of the value in <code>s1</code> and bind
it to <code>s2</code>. But this isnt quite what happens.</p>
<p>Take a look at Figure 4-1 to see what is happening to <code>String</code> under the
covers. A <code>String</code> is made up of three parts, shown on the left: a pointer to
the memory that holds the contents of the string, a length, and a capacity.
This group of data is stored on the stack. On the right is the memory on the
heap that holds the contents.</p>
<p><img alt="Two tables: the first table contains the representation of s1 on the
stack, consisting of its length (5), capacity (5), and a pointer to the first
value in the second table. The second table contains the representation of the
string data on the heap, byte by byte." src="../img/trpl04-01.svg" class="center" style="width: 50%;" /></p>
<p><span class="caption">Figure 4-1: The representation in memory of a <code>String</code>
holding the value <code>"hello"</code> bound to <code>s1</code></span></p>
<p>The length is how much memory, in bytes, the contents of the <code>String</code> are
currently using. The capacity is the total amount of memory, in bytes, that the
<code>String</code> has received from the allocator. The difference between length and
capacity matters, but not in this context, so for now, its fine to ignore the
capacity.</p>
<p>When we assign <code>s1</code> to <code>s2</code>, the <code>String</code> data is copied, meaning we copy the
pointer, the length, and the capacity that are on the stack. We do not copy the
data on the heap that the pointer refers to. In other words, the data
representation in memory looks like Figure 4-2.</p>
<p><img alt="Three tables: tables s1 and s2 representing those strings on the
stack, respectively, and both pointing to the same string data on the heap." src="../img/trpl04-02.svg" class="center" style="width: 50%;" /></p>
<p><span class="caption">Figure 4-2: The representation in memory of the variable
<code>s2</code> that has a copy of the pointer, length, and capacity of <code>s1</code></span></p>
<p>The representation does <em>not</em> look like Figure 4-3, which is what memory would
look like if Rust instead copied the heap data as well. If Rust did this, the
operation <code>s2 = s1</code> could be very expensive in terms of runtime performance if
the data on the heap were large.</p>
<p><img alt="Four tables: two tables representing the stack data for s1 and s2,
and each points to its own copy of string data on the heap." src="../img/trpl04-03.svg" class="center" style="width: 50%;" /></p>
<p><span class="caption">Figure 4-3: Another possibility for what <code>s2 = s1</code> might
do if Rust copied the heap data as well</span></p>
<p>Earlier, we said that when a variable goes out of scope, Rust automatically
calls the <code>drop</code> function and cleans up the heap memory for that variable. But
Figure 4-2 shows both data pointers pointing to the same location. This is a
problem: When <code>s2</code> and <code>s1</code> go out of scope, they will both try to free the
same memory. This is known as a <em>double free</em> error and is one of the memory
safety bugs we mentioned previously. Freeing memory twice can lead to memory
corruption, which can potentially lead to security vulnerabilities.</p>
<p>To ensure memory safety, after the line <code>let s2 = s1;</code>, Rust considers <code>s1</code> as
no longer valid. Therefore, Rust doesnt need to free anything when <code>s1</code> goes
out of scope. Check out what happens when you try to use <code>s1</code> after <code>s2</code> is
created; it wont work:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let s1 = String::from("hello");
let s2 = s1;
println!("{s1}, world!");
<span class="boring">}</span></code></pre>
<p>Youll get an error like this because Rust prevents you from using the
invalidated reference:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0382]: borrow of moved value: `s1`
--&gt; src/main.rs:5:16
|
2 | let s1 = String::from("hello");
| -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 | let s2 = s1;
| -- value moved here
4 |
5 | println!("{s1}, world!");
| ^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
|
3 | let s2 = s1.clone();
| ++++++++
For more information about this error, try `rustc --explain E0382`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>If youve heard the terms <em>shallow copy</em> and <em>deep copy</em> while working with
other languages, the concept of copying the pointer, length, and capacity
without copying the data probably sounds like making a shallow copy. But
because Rust also invalidates the first variable, instead of being called a
shallow copy, its known as a <em>move</em>. In this example, we would say that <code>s1</code>
was <em>moved</em> into <code>s2</code>. So, what actually happens is shown in Figure 4-4.</p>
<p><img alt="Three tables: tables s1 and s2 representing those strings on the
stack, respectively, and both pointing to the same string data on the heap.
Table s1 is grayed out because s1 is no longer valid; only s2 can be used to
access the heap data." src="../img/trpl04-04.svg" class="center" style="width:
50%;" /></p>
<p><span class="caption">Figure 4-4: The representation in memory after <code>s1</code> has
been invalidated</span></p>
<p>That solves our problem! With only <code>s2</code> valid, when it goes out of scope it
alone will free the memory, and were done.</p>
<p>In addition, theres a design choice thats implied by this: Rust will never
automatically create “deep” copies of your data. Therefore, any <em>automatic</em>
copying can be assumed to be inexpensive in terms of runtime performance.</p>
<h4 id="scope-and-assignment"><a class="header" href="#scope-and-assignment">Scope and Assignment</a></h4>
<p>The inverse of this is true for the relationship between scoping, ownership, and
memory being freed via the <code>drop</code> function as well. When you assign a completely
new value to an existing variable, Rust will call <code>drop</code> and free the original
values memory immediately. Consider this code, for example:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
s = String::from("ahoy");
println!("{s}, world!");
<span class="boring">}</span></code></pre>
<p>We initially declare a variable <code>s</code> and bind it to a <code>String</code> with the value
<code>"hello"</code>. Then, we immediately create a new <code>String</code> with the value <code>"ahoy"</code>
and assign it to <code>s</code>. At this point, nothing is referring to the original value
on the heap at all. Figure 4-5 illustrates the stack and heap data now:</p>
<p><img alt="One table representing the string value on the stack, pointing to
the second piece of string data (ahoy) on the heap, with the original string
data (hello) grayed out because it cannot be accessed anymore." src="../img/trpl04-05.svg" class="center" style="width: 50%;" /></p>
<p><span class="caption">Figure 4-5: The representation in memory after the initial
value has been replaced in its entirety</span></p>
<p>The original string thus immediately goes out of scope. Rust will run the <code>drop</code>
function on it and its memory will be freed right away. When we print the value
at the end, it will be <code>"ahoy, world!"</code>.</p>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="ways-variables-and-data-interact-clone"></a></p>
<h4 id="variables-and-data-interacting-with-clone"><a class="header" href="#variables-and-data-interacting-with-clone">Variables and Data Interacting with Clone</a></h4>
<p>If we <em>do</em> want to deeply copy the heap data of the <code>String</code>, not just the
stack data, we can use a common method called <code>clone</code>. Well discuss method
syntax in Chapter 5, but because methods are a common feature in many
programming languages, youve probably seen them before.</p>
<p>Heres an example of the <code>clone</code> method in action:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {s1}, s2 = {s2}");
<span class="boring">}</span></code></pre>
<p>This works just fine and explicitly produces the behavior shown in Figure 4-3,
where the heap data <em>does</em> get copied.</p>
<p>When you see a call to <code>clone</code>, you know that some arbitrary code is being
executed and that code may be expensive. Its a visual indicator that something
different is going on.</p>
<h4 id="stack-only-data-copy"><a class="header" href="#stack-only-data-copy">Stack-Only Data: Copy</a></h4>
<p>Theres another wrinkle we havent talked about yet. This code using
integers—part of which was shown in Listing 4-2—works and is valid:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let x = 5;
let y = x;
println!("x = {x}, y = {y}");
<span class="boring">}</span></code></pre>
<p>But this code seems to contradict what we just learned: We dont have a call to
<code>clone</code>, but <code>x</code> is still valid and wasnt moved into <code>y</code>.</p>
<p>The reason is that types such as integers that have a known size at compile
time are stored entirely on the stack, so copies of the actual values are quick
to make. That means theres no reason we would want to prevent <code>x</code> from being
valid after we create the variable <code>y</code>. In other words, theres no difference
between deep and shallow copying here, so calling <code>clone</code> wouldnt do anything
different from the usual shallow copying, and we can leave it out.</p>
<p>Rust has a special annotation called the <code>Copy</code> trait that we can place on
types that are stored on the stack, as integers are (well talk more about
traits in <a href="../ch10/ch10-02-traits.html">Chapter 10</a><!-- ignore -->). If a type implements the <code>Copy</code>
trait, variables that use it do not move, but rather are trivially copied,
making them still valid after assignment to another variable.</p>
<p>Rust wont let us annotate a type with <code>Copy</code> if the type, or any of its parts,
has implemented the <code>Drop</code> trait. If the type needs something special to happen
when the value goes out of scope and we add the <code>Copy</code> annotation to that type,
well get a compile-time error. To learn about how to add the <code>Copy</code> annotation
to your type to implement the trait, see <a href="../appendix/appendix-03-derivable-traits.html">“Derivable
Traits”</a><!-- ignore --> in Appendix C.</p>
<p>So, what types implement the <code>Copy</code> trait? You can check the documentation for
the given type to be sure, but as a general rule, any group of simple scalar
values can implement <code>Copy</code>, and nothing that requires allocation or is some
form of resource can implement <code>Copy</code>. Here are some of the types that
implement <code>Copy</code>:</p>
<ul>
<li>All the integer types, such as <code>u32</code>.</li>
<li>The Boolean type, <code>bool</code>, with values <code>true</code> and <code>false</code>.</li>
<li>All the floating-point types, such as <code>f64</code>.</li>
<li>The character type, <code>char</code>.</li>
<li>Tuples, if they only contain types that also implement <code>Copy</code>. For example,
<code>(i32, i32)</code> implements <code>Copy</code>, but <code>(i32, String)</code> does not.</li>
</ul>
<h3 id="ownership-and-functions"><a class="header" href="#ownership-and-functions">Ownership and Functions</a></h3>
<p>The mechanics of passing a value to a function are similar to those when
assigning a value to a variable. Passing a variable to a function will move or
copy, just as assignment does. Listing 4-3 has an example with some annotations
showing where variables go into and out of scope.</p>
<figure class="listing" id="listing-4-3">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">fn main() {
let s = String::from("hello"); // s comes into scope
takes_ownership(s); // s's value moves into the function...
// ... and so is no longer valid here
let x = 5; // x comes into scope
makes_copy(x); // Because i32 implements the Copy trait,
// x does NOT move into the function,
// so it's okay to use x afterward.
} // Here, x goes out of scope, then s. However, because s's value was moved,
// nothing special happens.
fn takes_ownership(some_string: String) { // some_string comes into scope
println!("{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!("{some_integer}");
} // Here, some_integer goes out of scope. Nothing special happens.</code></pre>
<figcaption><a href="#listing-4-3">Listing 4-3</a>: Functions with ownership and scope annotated</figcaption>
</figure>
<p>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. Try adding
code to <code>main</code> that uses <code>s</code> and <code>x</code> to see where you can use them and where
the ownership rules prevent you from doing so.</p>
<h3 id="return-values-and-scope"><a class="header" href="#return-values-and-scope">Return Values and Scope</a></h3>
<p>Returning values can also transfer ownership. Listing 4-4 shows an example of a
function that returns some value, with similar annotations as those in Listing
4-3.</p>
<figure class="listing" id="listing-4-4">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1
let s2 = String::from("hello"); // 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 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("yours"); // some_string comes into scope
some_string // some_string is returned and
// moves out to the calling
// function
}
// This function takes a String and returns a String.
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>
<figcaption><a href="#listing-4-4">Listing 4-4</a>: Transferring ownership of return values</figcaption>
</figure>
<p>The ownership of a variable follows the same pattern every time: Assigning a
value to another variable moves it. When a variable that includes data on the
heap goes out of scope, the value will be cleaned up by <code>drop</code> unless ownership
of the data has been moved to another variable.</p>
<p>While this works, taking ownership and then returning ownership with every
function is a bit tedious. What if we want to let a function use a value but
not take ownership? Its quite annoying that anything we pass in also needs to
be passed back if we want to use it again, in addition to any data resulting
from the body of the function that we might want to return as well.</p>
<p>Rust does let us return multiple values using a tuple, as shown in Listing 4-5.</p>
<figure class="listing" id="listing-4-5">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("The length of '{s2}' is {len}.");
}
fn calculate_length(s: String) -&gt; (String, usize) {
let length = s.len(); // len() returns the length of a String
(s, length)
}</code></pre>
<figcaption><a href="#listing-4-5">Listing 4-5</a>: Returning ownership of parameters</figcaption>
</figure>
<p>But this is too much ceremony and a lot of work for a concept that should be
common. Luckily for us, Rust has a feature for using a value without
transferring ownership: references.</p>
</body>
</html>

View File

@@ -0,0 +1,352 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>References and Borrowing</title>
</head>
<body>
<h2 id="references-and-borrowing"><a class="header" href="#references-and-borrowing">References and Borrowing</a></h2>
<p>The issue with the tuple code in Listing 4-5 is that we have to return the
<code>String</code> to the calling function so that we can still use the <code>String</code> after
the call to <code>calculate_length</code>, because the <code>String</code> was moved into
<code>calculate_length</code>. Instead, we can provide a reference to the <code>String</code> value.
A reference is like a pointer in that its an address we can follow to access
the data stored at that address; that data is owned by some other variable.
Unlike a pointer, a reference is guaranteed to point to a valid value of a
particular type for the life of that reference.</p>
<p>Here is how you would define and use a <code>calculate_length</code> function that has a
reference to an object as a parameter instead of taking ownership of the value:</p>
<figure class="listing">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">fn main() {
let s1 = String::from("hello");
let len = calculate_length(&amp;s1);
println!("The length of '{s1}' is {len}.");
}
fn calculate_length(s: &amp;String) -&gt; usize {
s.len()
}</code></pre>
</figure>
<p>First, notice that all the tuple code in the variable declaration and the
function return value is gone. Second, note that we pass <code>&amp;s1</code> into
<code>calculate_length</code> and, in its definition, we take <code>&amp;String</code> rather than
<code>String</code>. These ampersands represent references, and they allow you to refer to
some value without taking ownership of it. Figure 4-6 depicts this concept.</p>
<p><img alt="Three tables: the table for s contains only a pointer to the table
for s1. The table for s1 contains the stack data for s1 and points to the
string data on the heap." src="../img/trpl04-06.svg" class="center" /></p>
<p><span class="caption">Figure 4-6: A diagram of <code>&amp;String</code> <code>s</code> pointing at
<code>String</code> <code>s1</code></span></p>
<section class="note" aria-role="note">
<p>Note: The opposite of referencing by using <code>&amp;</code> is <em>dereferencing</em>, which is
accomplished with the dereference operator, <code>*</code>. Well see some uses of the
dereference operator in Chapter 8 and discuss details of dereferencing in
Chapter 15.</p>
</section>
<p>Lets take a closer look at the function call here:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let s1 = String::from("hello");
let len = calculate_length(&amp;s1);
<span class="boring">
</span><span class="boring"> println!("The length of '{s1}' is {len}.");
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn calculate_length(s: &amp;String) -&gt; usize {
</span><span class="boring"> s.len()
</span><span class="boring">}</span></code></pre>
<p>The <code>&amp;s1</code> syntax lets us create a reference that <em>refers</em> to the value of <code>s1</code>
but does not own it. Because the reference does not own it, the value it points
to will not be dropped when the reference stops being used.</p>
<p>Likewise, the signature of the function uses <code>&amp;</code> to indicate that the type of
the parameter <code>s</code> is a reference. Lets add some explanatory annotations:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span><span class="boring"> let s1 = String::from("hello");
</span><span class="boring">
</span><span class="boring"> let len = calculate_length(&amp;s1);
</span><span class="boring">
</span><span class="boring"> println!("The length of '{s1}' is {len}.");
</span><span class="boring">}
</span><span class="boring">
</span>fn calculate_length(s: &amp;String) -&gt; usize { // s is a reference to a String
s.len()
} // Here, s goes out of scope. But because s does not have ownership of what
// it refers to, the String is not dropped.</code></pre>
<p>The scope in which the variable <code>s</code> is valid is the same as any function
parameters scope, but the value pointed to by the reference is not dropped
when <code>s</code> stops being used, because <code>s</code> doesnt have ownership. When functions
have references as parameters instead of the actual values, we wont need to
return the values in order to give back ownership, because we never had
ownership.</p>
<p>We call the action of creating a reference <em>borrowing</em>. As in real life, if a
person owns something, you can borrow it from them. When youre done, you have
to give it back. You dont own it.</p>
<p>So, what happens if we try to modify something were borrowing? Try the code in
Listing 4-6. Spoiler alert: It doesnt work!</p>
<figure class="listing" id="listing-4-6">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let s = String::from("hello");
change(&amp;s);
}
fn change(some_string: &amp;String) {
some_string.push_str(", world");
}</code></pre>
<figcaption><a href="#listing-4-6">Listing 4-6</a>: Attempting to modify a borrowed value</figcaption>
</figure>
<p>Heres the error:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&amp;` reference
--&gt; src/main.rs:8:5
|
8 | some_string.push_str(", world");
| ^^^^^^^^^^^ `some_string` is a `&amp;` reference, so the data it refers to cannot be borrowed as mutable
|
help: consider changing this to be a mutable reference
|
7 | fn change(some_string: &amp;mut String) {
| +++
For more information about this error, try `rustc --explain E0596`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>Just as variables are immutable by default, so are references. Were not
allowed to modify something we have a reference to.</p>
<h3 id="mutable-references"><a class="header" href="#mutable-references">Mutable References</a></h3>
<p>We can fix the code from Listing 4-6 to allow us to modify a borrowed value
with just a few small tweaks that use, instead, a <em>mutable reference</em>:</p>
<figure class="listing">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">fn main() {
let mut s = String::from("hello");
change(&amp;mut s);
}
fn change(some_string: &amp;mut String) {
some_string.push_str(", world");
}</code></pre>
</figure>
<p>First, we change <code>s</code> to be <code>mut</code>. Then, we create a mutable reference with
<code>&amp;mut s</code> where we call the <code>change</code> function and update the function signature
to accept a mutable reference with <code>some_string: &amp;mut String</code>. This makes it
very clear that the <code>change</code> function will mutate the value it borrows.</p>
<p>Mutable references have one big restriction: If you have a mutable reference to
a value, you can have no other references to that value. This code that
attempts to create two mutable references to <code>s</code> will fail:</p>
<figure class="listing">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
let r1 = &amp;mut s;
let r2 = &amp;mut s;
println!("{r1}, {r2}");
<span class="boring">}</span></code></pre>
</figure>
<p>Heres the error:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0499]: cannot borrow `s` as mutable more than once at a time
--&gt; src/main.rs:5:14
|
4 | let r1 = &amp;mut s;
| ------ first mutable borrow occurs here
5 | let r2 = &amp;mut s;
| ^^^^^^ second mutable borrow occurs here
6 |
7 | println!("{r1}, {r2}");
| -- first borrow later used here
For more information about this error, try `rustc --explain E0499`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>This error says that this code is invalid because we cannot borrow <code>s</code> as
mutable more than once at a time. The first mutable borrow is in <code>r1</code> and must
last until its used in the <code>println!</code>, but between the creation of that
mutable reference and its usage, we tried to create another mutable reference
in <code>r2</code> that borrows the same data as <code>r1</code>.</p>
<p>The restriction preventing multiple mutable references to the same data at the
same time allows for mutation but in a very controlled fashion. Its something
that new Rustaceans struggle with because most languages let you mutate
whenever youd like. The benefit of having this restriction is that Rust can
prevent data races at compile time. A <em>data race</em> is similar to a race
condition and happens when these three behaviors occur:</p>
<ul>
<li>Two or more pointers access the same data at the same time.</li>
<li>At least one of the pointers is being used to write to the data.</li>
<li>Theres no mechanism being used to synchronize access to the data.</li>
</ul>
<p>Data races cause undefined behavior and can be difficult to diagnose and fix
when youre trying to track them down at runtime; Rust prevents this problem by
refusing to compile code with data races!</p>
<p>As always, we can use curly brackets to create a new scope, allowing for
multiple mutable references, just not <em>simultaneous</em> ones:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
{
let r1 = &amp;mut s;
} // r1 goes out of scope here, so we can make a new reference with no problems.
let r2 = &amp;mut s;
<span class="boring">}</span></code></pre>
<p>Rust enforces a similar rule for combining mutable and immutable references.
This code results in an error:</p>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
let r1 = &amp;s; // no problem
let r2 = &amp;s; // no problem
let r3 = &amp;mut s; // BIG PROBLEM
println!("{r1}, {r2}, and {r3}");
<span class="boring">}</span></code></pre>
<p>Heres the error:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--&gt; src/main.rs:6:14
|
4 | let r1 = &amp;s; // no problem
| -- immutable borrow occurs here
5 | let r2 = &amp;s; // no problem
6 | let r3 = &amp;mut s; // BIG PROBLEM
| ^^^^^^ mutable borrow occurs here
7 |
8 | println!("{r1}, {r2}, and {r3}");
| -- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>Whew! We <em>also</em> cannot have a mutable reference while we have an immutable one
to the same value.</p>
<p>Users of an immutable reference dont expect the value to suddenly change out
from under them! However, multiple immutable references are allowed because no
one who is just reading the data has the ability to affect anyone elses
reading of the data.</p>
<p>Note that a references scope starts from where it is introduced and continues
through the last time that reference is used. For instance, this code will
compile because the last usage of the immutable references is in the <code>println!</code>,
before the mutable reference is introduced:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let mut s = String::from("hello");
let r1 = &amp;s; // no problem
let r2 = &amp;s; // no problem
println!("{r1} and {r2}");
// Variables r1 and r2 will not be used after this point.
let r3 = &amp;mut s; // no problem
println!("{r3}");
<span class="boring">}</span></code></pre>
<p>The scopes of the immutable references <code>r1</code> and <code>r2</code> end after the <code>println!</code>
where they are last used, which is before the mutable reference <code>r3</code> is
created. These scopes dont overlap, so this code is allowed: The compiler can
tell that the reference is no longer being used at a point before the end of
the scope.</p>
<p>Even though borrowing errors may be frustrating at times, remember that its
the Rust compiler pointing out a potential bug early (at compile time rather
than at runtime) and showing you exactly where the problem is. Then, you dont
have to track down why your data isnt what you thought it was.</p>
<h3 id="dangling-references"><a class="header" href="#dangling-references">Dangling References</a></h3>
<p>In languages with pointers, its easy to erroneously create a <em>dangling
pointer</em>—a pointer that references a location in memory that may have been
given to someone else—by freeing some memory while preserving a pointer to that
memory. In Rust, by contrast, the compiler guarantees that references will
never be dangling references: If you have a reference to some data, the
compiler will ensure that the data will not go out of scope before the
reference to the data does.</p>
<p>Lets try to create a dangling reference to see how Rust prevents them with a
compile-time error:</p>
<figure class="listing">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore does_not_compile">fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -&gt; &amp;String {
let s = String::from("hello");
&amp;s
}</code></pre>
</figure>
<p>Heres the error:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0106]: missing lifetime specifier
--&gt; src/main.rs:5:16
|
5 | fn dangle() -&gt; &amp;String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
5 | fn dangle() -&gt; &amp;'static String {
| +++++++
help: instead, you are more likely to want to return an owned value
|
5 - fn dangle() -&gt; &amp;String {
5 + fn dangle() -&gt; String {
|
For more information about this error, try `rustc --explain E0106`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>This error message refers to a feature we havent covered yet: lifetimes. Well
discuss lifetimes in detail in Chapter 10. But, if you disregard the parts
about lifetimes, the message does contain the key to why this code is a problem:</p>
<pre><code class="language-text">this function's return type contains a borrowed value, but there is no value
for it to be borrowed from
</code></pre>
<p>Lets take a closer look at exactly whats happening at each stage of our
<code>dangle</code> code:</p>
<figure class="listing">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span><span class="boring"> let reference_to_nothing = dangle();
</span><span class="boring">}
</span><span class="boring">
</span>fn dangle() -&gt; &amp;String { // dangle returns a reference to a String
let s = String::from("hello"); // s is a new String
&amp;s // we return a reference to the String, s
} // Here, s goes out of scope and is dropped, so its memory goes away.
// Danger!</code></pre>
</figure>
<p>Because <code>s</code> is created inside <code>dangle</code>, when the code of <code>dangle</code> is finished,
<code>s</code> will be deallocated. But we tried to return a reference to it. That means
this reference would be pointing to an invalid <code>String</code>. Thats no good! Rust
wont let us do this.</p>
<p>The solution here is to return the <code>String</code> directly:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span><span class="boring"> let string = no_dangle();
</span><span class="boring">}
</span><span class="boring">
</span>fn no_dangle() -&gt; String {
let s = String::from("hello");
s
}</code></pre>
<p>This works without any problems. Ownership is moved out, and nothing is
deallocated.</p>
<h3 id="the-rules-of-references"><a class="header" href="#the-rules-of-references">The Rules of References</a></h3>
<p>Lets recap what weve discussed about references:</p>
<ul>
<li>At any given time, you can have <em>either</em> one mutable reference <em>or</em> any
number of immutable references.</li>
<li>References must always be valid.</li>
</ul>
<p>Next, well look at a different kind of reference: slices.</p>
</body>
</html>

429
ch04/ch04-03-slices.html Normal file
View File

@@ -0,0 +1,429 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Slice Type</title>
</head>
<body>
<h2 id="the-slice-type"><a class="header" href="#the-slice-type">The Slice Type</a></h2>
<p><em>Slices</em> let you reference a contiguous sequence of elements in a
<a href="../ch08/ch08-00-common-collections.html">collection</a><!-- ignore -->. A slice is a kind
of reference, so it does not have ownership.</p>
<p>Heres a small programming problem: Write a function that takes a string of
words separated by spaces and returns the first word it finds in that string.
If the function doesnt find a space in the string, the whole string must be
one word, so the entire string should be returned.</p>
<section class="note" aria-role="note">
<p>Note: For the purposes of introducing slices, we are assuming ASCII only in
this section; a more thorough discussion of UTF-8 handling is in the
<a href="../ch08/ch08-02-strings.html#storing-utf-8-encoded-text-with-strings">“Storing UTF-8 Encoded Text with Strings”</a><!-- ignore --> section
of Chapter 8.</p>
</section>
<p>Lets work through how wed write the signature of this function without using
slices, to understand the problem that slices will solve:</p>
<pre><code class="language-rust ignore">fn first_word(s: &amp;String) -&gt; ?</code></pre>
<p>The <code>first_word</code> function has a parameter of type <code>&amp;String</code>. We dont need
ownership, so this is fine. (In idiomatic Rust, functions do not take ownership
of their arguments unless they need to, and the reasons for that will become
clear as we keep going.) But what should we return? We dont really have a way
to talk about <em>part</em> of a string. However, we could return the index of the end
of the word, indicated by a space. Lets try that, as shown in Listing 4-7.</p>
<figure class="listing" id="listing-4-7">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">fn first_word(s: &amp;String) -&gt; usize {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<figcaption><a href="#listing-4-7">Listing 4-7</a>: The <code>first_word</code> function that returns a byte index value into the <code>String</code> parameter</figcaption>
</figure>
<p>Because we need to go through the <code>String</code> element by element and check whether
a value is a space, well convert our <code>String</code> to an array of bytes using the
<code>as_bytes</code> method.</p>
<pre><code class="language-rust ignore"><span class="boring">fn first_word(s: &amp;String) -&gt; usize {
</span> let bytes = s.as_bytes();
<span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return i;
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> s.len()
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<p>Next, we create an iterator over the array of bytes using the <code>iter</code> method:</p>
<pre><code class="language-rust ignore"><span class="boring">fn first_word(s: &amp;String) -&gt; usize {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span> for (i, &amp;item) in bytes.iter().enumerate() {
<span class="boring"> if item == b' ' {
</span><span class="boring"> return i;
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> s.len()
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<p>Well discuss iterators in more detail in <a href="../ch13/ch13-02-iterators.html">Chapter 13</a><!-- ignore -->.
For now, know that <code>iter</code> is a method that returns each element in a collection
and that <code>enumerate</code> wraps the result of <code>iter</code> and returns each element as
part of a tuple instead. The first element of the tuple returned from
<code>enumerate</code> is the index, and the second element is a reference to the element.
This is a bit more convenient than calculating the index ourselves.</p>
<p>Because the <code>enumerate</code> method returns a tuple, we can use patterns to
destructure that tuple. Well be discussing patterns more in <a href="../ch06/ch06-02-match.html#patterns-that-bind-to-values">Chapter
6</a><!-- ignore -->. In the <code>for</code> loop, we specify a pattern that has <code>i</code>
for the index in the tuple and <code>&amp;item</code> for the single byte in the tuple.
Because we get a reference to the element from <code>.iter().enumerate()</code>, we use
<code>&amp;</code> in the pattern.</p>
<p>Inside the <code>for</code> loop, we search for the byte that represents the space by
using the byte literal syntax. If we find a space, we return the position.
Otherwise, we return the length of the string by using <code>s.len()</code>.</p>
<pre><code class="language-rust ignore"><span class="boring">fn first_word(s: &amp;String) -&gt; usize {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span> if item == b' ' {
return i;
}
}
s.len()
<span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
<p>We now have a way to find out the index of the end of the first word in the
string, but theres a problem. Were returning a <code>usize</code> on its own, but its
only a meaningful number in the context of the <code>&amp;String</code>. In other words,
because its a separate value from the <code>String</code>, theres no guarantee that it
will still be valid in the future. Consider the program in Listing 4-8 that
uses the <code>first_word</code> function from Listing 4-7.</p>
<figure class="listing" id="listing-4-8">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn first_word(s: &amp;String) -&gt; usize {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return i;
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> s.len()
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let mut s = String::from("hello world");
let word = first_word(&amp;s); // word will get the value 5
s.clear(); // this empties the String, making it equal to ""
// word still has the value 5 here, but s no longer has any content that we
// could meaningfully use with the value 5, so word is now totally invalid!
}</code></pre>
<figcaption><a href="#listing-4-8">Listing 4-8</a>: Storing the result from calling the <code>first_word</code> function and then changing the <code>String</code> contents</figcaption>
</figure>
<p>This program compiles without any errors and would also do so if we used <code>word</code>
after calling <code>s.clear()</code>. Because <code>word</code> isnt connected to the state of <code>s</code>
at all, <code>word</code> still contains the value <code>5</code>. We could use that value <code>5</code> with
the variable <code>s</code> to try to extract the first word out, but this would be a bug
because the contents of <code>s</code> have changed since we saved <code>5</code> in <code>word</code>.</p>
<p>Having to worry about the index in <code>word</code> getting out of sync with the data in
<code>s</code> is tedious and error-prone! Managing these indices is even more brittle if
we 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 were tracking a starting <em>and</em> an ending index, and we have even more
values that were calculated from data in a particular state but arent tied to
that state at all. We have three unrelated variables floating around that need
to be kept in sync.</p>
<p>Luckily, Rust has a solution to this problem: string slices.</p>
<h3 id="string-slices"><a class="header" href="#string-slices">String Slices</a></h3>
<p>A <em>string slice</em> is a reference to a contiguous sequence of the elements of a
<code>String</code>, and it looks like this:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let s = String::from("hello world");
let hello = &amp;s[0..5];
let world = &amp;s[6..11];
<span class="boring">}</span></code></pre>
<p>Rather than a reference to the entire <code>String</code>, <code>hello</code> is a reference to a
portion of the <code>String</code>, specified in the extra <code>[0..5]</code> bit. We create slices
using a range within square brackets by specifying
<code>[starting_index..ending_index]</code>, where <em><code>starting_index</code></em> is the first
position in the slice and <em><code>ending_index</code></em> is one more than the last position
in the slice. Internally, the slice data structure stores the starting position
and the length of the slice, which corresponds to <em><code>ending_index</code></em> minus
<em><code>starting_index</code></em>. So, in the case of <code>let world = &amp;s[6..11];</code>, <code>world</code> would
be a slice that contains a pointer to the byte at index 6 of <code>s</code> with a length
value of <code>5</code>.</p>
<p>Figure 4-7 shows this in a diagram.</p>
<p><img alt="Three tables: a table representing the stack data of s, which points
to the byte at index 0 in a table of the string data &quot;hello world&quot; on
the heap. The third table represents the stack data of the slice world, which
has a length value of 5 and points to byte 6 of the heap data table." src="../img/trpl04-07.svg" class="center" style="width: 50%;" /></p>
<p><span class="caption">Figure 4-7: A string slice referring to part of a
<code>String</code></span></p>
<p>With Rusts <code>..</code> range syntax, if you want to start at index 0, you can drop
the value before the two periods. In other words, these are equal:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = String::from("hello");
let slice = &amp;s[0..2];
let slice = &amp;s[..2];
<span class="boring">}</span></code></pre>
<p>By the same token, if your slice includes the last byte of the <code>String</code>, you
can drop the trailing number. That means these are equal:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = String::from("hello");
let len = s.len();
let slice = &amp;s[3..len];
let slice = &amp;s[3..];
<span class="boring">}</span></code></pre>
<p>You can also drop both values to take a slice of the entire string. So, these
are equal:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = String::from("hello");
let len = s.len();
let slice = &amp;s[0..len];
let slice = &amp;s[..];
<span class="boring">}</span></code></pre>
<section class="note" aria-role="note">
<p>Note: String slice range indices must occur at valid UTF-8 character
boundaries. If you attempt to create a string slice in the middle of a
multibyte character, your program will exit with an error.</p>
</section>
<p>With all this information in mind, lets rewrite <code>first_word</code> to return a
slice. The type that signifies “string slice” is written as <code>&amp;str</code>:</p>
<figure class="listing">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">fn first_word(s: &amp;String) -&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[..]
}
<span class="boring">
</span><span class="boring">fn main() {}</span></code></pre>
</figure>
<p>We get the index for the end of the word the same way we did in Listing 4-7, by
looking for the first occurrence of a space. When we find a space, we return a
string slice using the start of the string and the index of the space as the
starting and ending indices.</p>
<p>Now when we call <code>first_word</code>, we get back a single value that is tied to the
underlying data. The value is made up of a reference to the starting point of
the slice and the number of elements in the slice.</p>
<p>Returning a slice would also work for a <code>second_word</code> function:</p>
<pre><code class="language-rust ignore">fn second_word(s: &amp;String) -&gt; &amp;str {</code></pre>
<p>We now have a straightforward API thats much harder to mess up because the
compiler will ensure that the references into the <code>String</code> remain valid.
Remember the bug in the program in Listing 4-8, when we got the index to the
end of the first word but then cleared the string so our index was invalid?
That code was logically incorrect but didnt show any immediate errors. The
problems would show up later if we kept trying to use the first word index with
an emptied string. Slices make this bug impossible and let us know much sooner
that we have a problem with our code. Using the slice version of <code>first_word</code>
will throw a compile-time error:</p>
<figure class="listing">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn first_word(s: &amp;String) -&gt; &amp;str {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return &amp;s[0..i];
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> &amp;s[..]
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let mut s = String::from("hello world");
let word = first_word(&amp;s);
s.clear(); // error!
println!("the first word is: {word}");
}</code></pre>
</figure>
<p>Heres the compiler error:</p>
<pre><code class="language-console">$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--&gt; src/main.rs:18:5
|
16 | let word = first_word(&amp;s);
| -- immutable borrow occurs here
17 |
18 | s.clear(); // error!
| ^^^^^^^^^ mutable borrow occurs here
19 |
20 | println!("the first word is: {word}");
| ---- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` (bin "ownership") due to 1 previous error
</code></pre>
<p>Recall from the borrowing rules that if we have an immutable reference to
something, we cannot also take a mutable reference. Because <code>clear</code> needs to
truncate the <code>String</code>, it needs to get a mutable reference. The <code>println!</code>
after the call to <code>clear</code> uses the reference in <code>word</code>, so the immutable
reference must still be active at that point. Rust disallows the mutable
reference in <code>clear</code> and the immutable reference in <code>word</code> from existing at the
same time, and compilation fails. Not only has Rust made our API easier to use,
but it has also eliminated an entire class of errors at compile time!</p>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="string-literals-are-slices"></a></p>
<h4 id="string-literals-as-slices"><a class="header" href="#string-literals-as-slices">String Literals as Slices</a></h4>
<p>Recall that we talked about string literals being stored inside the binary. Now
that we know about slices, we can properly understand string literals:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let s = "Hello, world!";
<span class="boring">}</span></code></pre>
<p>The type of <code>s</code> here is <code>&amp;str</code>: Its 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>
<h4 id="string-slices-as-parameters"><a class="header" href="#string-slices-as-parameters">String Slices as Parameters</a></h4>
<p>Knowing that you can take slices of literals and <code>String</code> values leads us to
one more improvement on <code>first_word</code>, and thats 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 the signature shown in Listing 4-9
instead because it allows us to use the same function on both <code>&amp;String</code> values
and <code>&amp;str</code> values.</p>
<figure class="listing" id="listing-4-9">
<pre><code class="language-rust ignore">fn first_word(s: &amp;str) -&gt; &amp;str {
<span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return &amp;s[0..i];
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> &amp;s[..]
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let my_string = String::from("hello world");
</span><span class="boring">
</span><span class="boring"> // `first_word` works on slices of `String`s, whether partial or whole.
</span><span class="boring"> let word = first_word(&amp;my_string[0..6]);
</span><span class="boring"> let word = first_word(&amp;my_string[..]);
</span><span class="boring"> // `first_word` also works on references to `String`s, which are equivalent
</span><span class="boring"> // to whole slices of `String`s.
</span><span class="boring"> let word = first_word(&amp;my_string);
</span><span class="boring">
</span><span class="boring"> let my_string_literal = "hello world";
</span><span class="boring">
</span><span class="boring"> // `first_word` works on slices of string literals, whether partial or
</span><span class="boring"> // whole.
</span><span class="boring"> let word = first_word(&amp;my_string_literal[0..6]);
</span><span class="boring"> let word = first_word(&amp;my_string_literal[..]);
</span><span class="boring">
</span><span class="boring"> // Because string literals *are* string slices already,
</span><span class="boring"> // this works too, without the slice syntax!
</span><span class="boring"> let word = first_word(my_string_literal);
</span><span class="boring">}</span></code></pre>
<figcaption><a href="#listing-4-9">Listing 4-9</a>: Improving the <code>first_word</code> function by using a string slice for the type of the <code>s</code> parameter</figcaption>
</figure>
<p>If we have a string slice, we can pass that directly. If we have a <code>String</code>, we
can pass a slice of the <code>String</code> or a reference to the <code>String</code>. This
flexibility takes advantage of deref coercions, a feature we will cover in
the <a href="../ch15/ch15-02-deref.html#using-deref-coercions-in-functions-and-methods">“Using Deref Coercions in Functions and Methods”</a><!--
ignore --> section of Chapter 15.</p>
<p>Defining a function to take a string slice instead of a reference to a <code>String</code>
makes our API more general and useful without losing any functionality:</p>
<figure class="listing">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn first_word(s: &amp;str) -&gt; &amp;str {
</span><span class="boring"> let bytes = s.as_bytes();
</span><span class="boring">
</span><span class="boring"> for (i, &amp;item) in bytes.iter().enumerate() {
</span><span class="boring"> if item == b' ' {
</span><span class="boring"> return &amp;s[0..i];
</span><span class="boring"> }
</span><span class="boring"> }
</span><span class="boring">
</span><span class="boring"> &amp;s[..]
</span><span class="boring">}
</span><span class="boring">
</span>fn main() {
let my_string = String::from("hello world");
// `first_word` works on slices of `String`s, whether partial or whole.
let word = first_word(&amp;my_string[0..6]);
let word = first_word(&amp;my_string[..]);
// `first_word` also works on references to `String`s, which are equivalent
// to whole slices of `String`s.
let word = first_word(&amp;my_string);
let my_string_literal = "hello world";
// `first_word` works on slices of string literals, whether partial or
// whole.
let word = first_word(&amp;my_string_literal[0..6]);
let word = first_word(&amp;my_string_literal[..]);
// Because string literals *are* string slices already,
// this works too, without the slice syntax!
let word = first_word(my_string_literal);
}</code></pre>
</figure>
<h3 id="other-slices"><a class="header" href="#other-slices">Other Slices</a></h3>
<p>String slices, as you might imagine, are specific to strings. But theres a
more general slice type too. Consider this array:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let a = [1, 2, 3, 4, 5];
<span class="boring">}</span></code></pre>
<p>Just as we might want to refer to part of a string, we might want to refer to
part of an array. Wed do so like this:</p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let a = [1, 2, 3, 4, 5];
let slice = &amp;a[1..3];
assert_eq!(slice, &amp;[2, 3]);
<span class="boring">}</span></code></pre>
<p>This slice has the type <code>&amp;[i32]</code>. It works the same way as string slices do, by
storing a reference to the first element and a length. Youll use this kind of
slice for all sorts of other collections. Well discuss these collections in
detail when we talk about vectors in Chapter 8.</p>
<h2 id="summary"><a class="header" href="#summary">Summary</a></h2>
<p>The concepts of ownership, borrowing, and slices ensure memory safety in Rust
programs at compile time. The Rust language gives you control over your memory
usage in the same way as other systems programming languages. But having the
owner of data automatically clean up that data when the owner goes out of scope
means you dont have to write and debug extra code to get this control.</p>
<p>Ownership affects how lots of other parts of Rust work, so well talk about
these concepts further throughout the rest of the book. Lets move on to
Chapter 5 and look at grouping pieces of data together in a <code>struct</code>.</p>
</body>
</html>