Files
docs-rust/ch08/ch08-01-vectors.html
2026-06-22 21:27:36 +05:30

268 lines
16 KiB
HTML
Raw Permalink 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>Storing Lists of Values with Vectors</title>
</head>
<body>
<h2 id="storing-lists-of-values-with-vectors"><a class="header" href="#storing-lists-of-values-with-vectors">Storing Lists of Values with Vectors</a></h2>
<p>The first collection type well look at is <code>Vec&lt;T&gt;</code>, also known as a vector.
Vectors allow you to store more than one value in a single data structure that
puts all the values next to each other in memory. Vectors can only store values
of the same type. They are useful when you have a list of items, such as the
lines of text in a file or the prices of items in a shopping cart.</p>
<h3 id="creating-a-new-vector"><a class="header" href="#creating-a-new-vector">Creating a New Vector</a></h3>
<p>To create a new, empty vector, we call the <code>Vec::new</code> function, as shown in
Listing 8-1.</p>
<figure class="listing" id="listing-8-1">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let v: Vec&lt;i32&gt; = Vec::new();
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-1">Listing 8-1</a>: Creating a new, empty vector to hold values of type <code>i32</code></figcaption>
</figure>
<p>Note that we added a type annotation here. Because we arent inserting any
values into this vector, Rust doesnt know what kind of elements we intend to
store. This is an important point. Vectors are implemented using generics;
well cover how to use generics with your own types in Chapter 10. For now,
know that the <code>Vec&lt;T&gt;</code> type provided by the standard library can hold any type.
When we create a vector to hold a specific type, we can specify the type within
angle brackets. In Listing 8-1, weve told Rust that the <code>Vec&lt;T&gt;</code> in <code>v</code> will
hold elements of the <code>i32</code> type.</p>
<p>More often, youll create a <code>Vec&lt;T&gt;</code> with initial values, and Rust will infer
the type of value you want to store, so you rarely need to do this type
annotation. Rust conveniently provides the <code>vec!</code> macro, which will create a
new vector that holds the values you give it. Listing 8-2 creates a new
<code>Vec&lt;i32&gt;</code> that holds the values <code>1</code>, <code>2</code>, and <code>3</code>. The integer type is <code>i32</code>
because thats the default integer type, as we discussed in the <a href="../ch03/ch03-02-data-types.html#data-types">“Data
Types”</a><!-- ignore --> section of Chapter 3.</p>
<figure class="listing" id="listing-8-2">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let v = vec![1, 2, 3];
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-2">Listing 8-2</a>: Creating a new vector containing values</figcaption>
</figure>
<p>Because weve given initial <code>i32</code> values, Rust can infer that the type of <code>v</code>
is <code>Vec&lt;i32&gt;</code>, and the type annotation isnt necessary. Next, well look at how
to modify a vector.</p>
<h3 id="updating-a-vector"><a class="header" href="#updating-a-vector">Updating a Vector</a></h3>
<p>To create a vector and then add elements to it, we can use the <code>push</code> method,
as shown in Listing 8-3.</p>
<figure class="listing" id="listing-8-3">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-3">Listing 8-3</a>: Using the <code>push</code> method to add values to a vector</figcaption>
</figure>
<p>As with any variable, if we want to be able to change its value, we need to
make it mutable using the <code>mut</code> keyword, as discussed in Chapter 3. The numbers
we place inside are all of type <code>i32</code>, and Rust infers this from the data, so
we dont need the <code>Vec&lt;i32&gt;</code> annotation.</p>
<h3 id="reading-elements-of-vectors"><a class="header" href="#reading-elements-of-vectors">Reading Elements of Vectors</a></h3>
<p>There are two ways to reference a value stored in a vector: via indexing or by
using the <code>get</code> method. In the following examples, weve annotated the types of
the values that are returned from these functions for extra clarity.</p>
<p>Listing 8-4 shows both methods of accessing a value in a vector, with indexing
syntax and the <code>get</code> method.</p>
<figure class="listing" id="listing-8-4">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let v = vec![1, 2, 3, 4, 5];
let third: &amp;i32 = &amp;v[2];
println!("The third element is {third}");
let third: Option&lt;&amp;i32&gt; = v.get(2);
match third {
Some(third) =&gt; println!("The third element is {third}"),
None =&gt; println!("There is no third element."),
}
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-4">Listing 8-4</a>: Using indexing syntax and using the <code>get</code> method to access an item in a vector</figcaption>
</figure>
<p>Note a few details here. We use the index value of <code>2</code> to get the third element
because vectors are indexed by number, starting at zero. Using <code>&amp;</code> and <code>[]</code>
gives us a reference to the element at the index value. When we use the <code>get</code>
method with the index passed as an argument, we get an <code>Option&lt;&amp;T&gt;</code> that we can
use with <code>match</code>.</p>
<p>Rust provides these two ways to reference an element so that you can choose how
the program behaves when you try to use an index value outside the range of
existing elements. As an example, lets see what happens when we have a vector
of five elements and then we try to access an element at index 100 with each
technique, as shown in Listing 8-5.</p>
<figure class="listing" id="listing-8-5">
<pre class="playground"><code class="language-rust should_panic panics edition2024"><span class="boring">fn main() {
</span> let v = vec![1, 2, 3, 4, 5];
let does_not_exist = &amp;v[100];
let does_not_exist = v.get(100);
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-5">Listing 8-5</a>: Attempting to access the element at index 100 in a vector containing five elements</figcaption>
</figure>
<p>When we run this code, the first <code>[]</code> method will cause the program to panic
because it references a nonexistent element. This method is best used when you
want your program to crash if theres an attempt to access an element past the
end of the vector.</p>
<p>When the <code>get</code> method is passed an index that is outside the vector, it returns
<code>None</code> without panicking. You would use this method if accessing an element
beyond the range of the vector may happen occasionally under normal
circumstances. Your code will then have logic to handle having either
<code>Some(&amp;element)</code> or <code>None</code>, as discussed in Chapter 6. For example, the index
could be coming from a person entering a number. If they accidentally enter a
number thats too large and the program gets a <code>None</code> value, you could tell the
user how many items are in the current vector and give them another chance to
enter a valid value. That would be more user-friendly than crashing the program
due to a typo!</p>
<p>When the program has a valid reference, the borrow checker enforces the
ownership and borrowing rules (covered in Chapter 4) to ensure that this
reference and any other references to the contents of the vector remain valid.
Recall the rule that states you cant have mutable and immutable references in
the same scope. That rule applies in Listing 8-6, where we hold an immutable
reference to the first element in a vector and try to add an element to the
end. This program wont work if we also try to refer to that element later in
the function.</p>
<figure class="listing" id="listing-8-6">
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
</span> let mut v = vec![1, 2, 3, 4, 5];
let first = &amp;v[0];
v.push(6);
println!("The first element is: {first}");
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-6">Listing 8-6</a>: Attempting to add an element to a vector while holding a reference to an item</figcaption>
</figure>
<p>Compiling this code will result in this error:</p>
<pre><code class="language-console">$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--&gt; src/main.rs:6:5
|
4 | let first = &amp;v[0];
| - immutable borrow occurs here
5 |
6 | v.push(6);
| ^^^^^^^^^ mutable borrow occurs here
7 |
8 | println!("The first element is: {first}");
| ----- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `collections` (bin "collections") due to 1 previous error
</code></pre>
<p>The code in Listing 8-6 might look like it should work: Why should a reference
to the first element care about changes at the end of the vector? This error is
due to the way vectors work: Because vectors put the values next to each other
in memory, adding a new element onto the end of the vector might require
allocating new memory and copying the old elements to the new space, if there
isnt enough room to put all the elements next to each other where the vector
is currently stored. In that case, the reference to the first element would be
pointing to deallocated memory. The borrowing rules prevent programs from
ending up in that situation.</p>
<section class="note" aria-role="note">
<p>Note: For more on the implementation details of the <code>Vec&lt;T&gt;</code> type, see <a href="../nomicon/vec/vec.html">“The
Rustonomicon”</a>.</p>
</section>
<h3 id="iterating-over-the-values-in-a-vector"><a class="header" href="#iterating-over-the-values-in-a-vector">Iterating Over the Values in a Vector</a></h3>
<p>To access each element in a vector in turn, we would iterate through all of the
elements rather than use indices to access one at a time. Listing 8-7 shows how
to use a <code>for</code> loop to get immutable references to each element in a vector of
<code>i32</code> values and print them.</p>
<figure class="listing" id="listing-8-7">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let v = vec![100, 32, 57];
for i in &amp;v {
println!("{i}");
}
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-7">Listing 8-7</a>: Printing each element in a vector by iterating over the elements using a <code>for</code> loop</figcaption>
</figure>
<p>We can also iterate over mutable references to each element in a mutable vector
in order to make changes to all the elements. The <code>for</code> loop in Listing 8-8
will add <code>50</code> to each element.</p>
<figure class="listing" id="listing-8-8">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> let mut v = vec![100, 32, 57];
for i in &amp;mut v {
*i += 50;
}
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-8">Listing 8-8</a>: Iterating over mutable references to elements in a vector</figcaption>
</figure>
<p>To change the value that the mutable reference refers to, we have to use the
<code>*</code> dereference operator to get to the value in <code>i</code> before we can use the <code>+=</code>
operator. Well talk more about the dereference operator in the <a href="../ch15/ch15-02-deref.html#following-the-pointer-to-the-value-with-the-dereference-operator">“Following the
Reference to the Value”</a><!-- ignore --> section of Chapter 15.</p>
<p>Iterating over a vector, whether immutably or mutably, is safe because of the
borrow checkers rules. If we attempted to insert or remove items in the <code>for</code>
loop bodies in Listing 8-7 and Listing 8-8, we would get a compiler error
similar to the one we got with the code in Listing 8-6. The reference to the
vector that the <code>for</code> loop holds prevents simultaneous modification of the
whole vector.</p>
<h3 id="using-an-enum-to-store-multiple-types"><a class="header" href="#using-an-enum-to-store-multiple-types">Using an Enum to Store Multiple Types</a></h3>
<p>Vectors can only store values that are of the same type. This can be
inconvenient; there are definitely use cases for needing to store a list of
items of different types. Fortunately, the variants of an enum are defined
under the same enum type, so when we need one type to represent elements of
different types, we can define and use an enum!</p>
<p>For example, say we want to get values from a row in a spreadsheet in which
some of the columns in the row contain integers, some floating-point numbers,
and some strings. We can define an enum whose variants will hold the different
value types, and all the enum variants will be considered the same type: that
of the enum. Then, we can create a vector to hold that enum and so, ultimately,
hold different types. Weve demonstrated this in Listing 8-9.</p>
<figure class="listing" id="listing-8-9">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
];
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-9">Listing 8-9</a>: Defining an enum to store values of different types in one vector</figcaption>
</figure>
<p>Rust needs to know what types will be in the vector at compile time so that it
knows exactly how much memory on the heap will be needed to store each element.
We must also be explicit about what types are allowed in this vector. If Rust
allowed a vector to hold any type, there would be a chance that one or more of
the types would cause errors with the operations performed on the elements of
the vector. Using an enum plus a <code>match</code> expression means that Rust will ensure
at compile time that every possible case is handled, as discussed in Chapter 6.</p>
<p>If you dont know the exhaustive set of types a program will get at runtime to
store in a vector, the enum technique wont work. Instead, you can use a trait
object, which well cover in Chapter 18.</p>
<p>Now that weve discussed some of the most common ways to use vectors, be sure
to review <a href="../std/vec/struct.Vec.html">the API documentation</a><!-- ignore --> for all of the many
useful methods defined on <code>Vec&lt;T&gt;</code> by the standard library. For example, in
addition to <code>push</code>, a <code>pop</code> method removes and returns the last element.</p>
<h3 id="dropping-a-vector-drops-its-elements"><a class="header" href="#dropping-a-vector-drops-its-elements">Dropping a Vector Drops Its Elements</a></h3>
<p>Like any other <code>struct</code>, a vector is freed when it goes out of scope, as
annotated in Listing 8-10.</p>
<figure class="listing" id="listing-8-10">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
</span> {
let v = vec![1, 2, 3, 4];
// do stuff with v
} // &lt;- v goes out of scope and is freed here
<span class="boring">}</span></code></pre>
<figcaption><a href="#listing-8-10">Listing 8-10</a>: Showing where the vector and its elements are dropped</figcaption>
</figure>
<p>When the vector gets dropped, all of its contents are also dropped, meaning the
integers it holds will be cleaned up. The borrow checker ensures that any
references to contents of a vector are only used while the vector itself is
valid.</p>
<p>Lets move on to the next collection type: <code>String</code>!</p>
</body>
</html>