Files
book/ch05-00-structs.html
T

443 lines
26 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>Structs - 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='https://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="https://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="https://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 class="light">
<!-- 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="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References &amp; Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html" class="active"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html"><strong>5.1.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums</a></li><li><ul class="section"><li><a href="ch06-01-option.html"><strong>6.1.</strong> Option</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> Match</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-fundamental-collections.html"><strong>8.</strong> Fundamental Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generics</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Syntax</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Lifetime syntax</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><a href="ch12-00-an-io-project.html"><strong>12.</strong> An I/O Project</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> Accepting Command Line Arguments</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> Reading a File</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> Improving Error Handling and Modularity</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> Testing the Library's Functionality</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> Working with Environment Variables</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> Writing to <code>stderr</code> instead of <code>stdout</code></a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Functional Language Features in Rust - Iterators and Closures</a></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></li><li><a href="ch15-00-smart-pointers.html"><strong>15.</strong> Smart Pointers</a></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> Concurrency</a></li><li><a href="ch17-00-oop.html"><strong>17.</strong> Is Rust OOP?</a></li><li><a href="ch18-00-patterns.html"><strong>18.</strong> Patterns</a></li><li><a href="ch19-00-more-lifetimes.html"><strong>19.</strong> More Lifetimes</a></li><li><a href="ch20-00-advanced-types.html"><strong>20.</strong> Advanced Type System Features</a></li><li><strong>21.</strong> Macros</li><li><ul class="section"><li><strong>21.1.</strong> Writing Your Own Macros</li></ul></li><li><a href="appendix-00.html"><strong>22.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>22.1.</strong> Keywords</a></li><li><a href="appendix-02-operators.html"><strong>22.2.</strong> Operators</a></li><li><a href="appendix-03-derivable-traits.html"><strong>22.3.</strong> Derivable Traits</a></li><li><a href="appendix-04-nightly-rust.html"><strong>22.4.</strong> Nightly Rust</a></li></ul></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>Structs</h1>
<p>A <code>struct</code>, short for <em>structure</em>, is a custom data type that lets us name and
package together multiple related values that make up a meaningful group. If
you come from an object-oriented language, a <code>struct</code> is like an object’s data
attributes. In the next section of this chapter, we’ll talk about how to define
methods on our structs; methods are how you specify the <em>behavior</em> that goes
along with a struct’s data. The <code>struct</code> and <code>enum</code> (that we will talk about in
Chapter 6) concepts are the building blocks for creating new types in your
program’s domain in order to take full advantage of Rust’s compile-time type
checking.</p>
<p>One way of thinking about structs is that they are similar to tuples, which we
talked about in Chapter 3. Like tuples, the pieces of a struct can be different
types. Unlike tuples, we name each piece of data so that it’s clearer what the
values mean. Structs are more flexible as a result of these names: we don’t
have to rely on the order of the data to specify or access the values of an
instance.</p>
<p>To define a struct, we enter the keyword <code>struct</code> and give the whole struct a
name. A struct’s name should describe what the significance is of these pieces
of data being grouped together. Then, inside curly braces, we define the names
of the pieces of data, which we call <em>fields</em>, and specify each field’s type.
For example, Listing 5-1 shows a struct to store information about a user
account:</p>
<figure>
<pre><code class="language-rust">struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
</code></pre>
<figcaption>
<p>Listing 5-1: A <code>User</code> struct definition</p>
</figcaption>
</figure>
<p>To use a struct once we've defined it, we create an <em>instance</em> of that struct
by specifying concrete values for each of the fields. Creating an instance is
done by stating the name of the struct, then curly braces with <code>key: value</code>
pairs inside it where the keys are the names of the fields and the values are
the data we want to store in those fields. The fields don’t have to be
specified in the same order in which the struct declared them. In other words,
the struct definition is like a general template for the type, and instances
fill in that template with particular data to create values of the type. For
example, we can declare a particular user like this:</p>
<pre><code class="language-rust"># struct User {
# username: String,
# email: String,
# sign_in_count: u64,
# active: bool,
# }
#
let user1 = User {
email: String::from(&quot;someone@example.com&quot;),
username: String::from(&quot;someusername123&quot;),
active: true,
sign_in_count: 1,
};
</code></pre>
<p>To get a particular value out of a struct, we can use dot notation. If we
wanted just this user’s email address, we can say <code>user1.email</code>.</p>
<h2>Ownership of Struct Data</h2>
<p>In the <code>User</code> struct definition in Listing 5-1, we used the owned <code>String</code> type
rather than the <code>&amp;str</code> string slice type. This is a deliberate choice because
we want instances of this struct to own all of its data, and for that data to
be valid for as long as the entire struct is valid.</p>
<p>It is possible for structs to store references to data owned by something else,
but to do so requires the use of <em>lifetimes</em>, a feature of Rust that we'll
discuss in Chapter 10. Lifetimes ensure that the data a struct references is
valid for as long as the struct is. If you try to store a reference in a struct
without specifying lifetimes, like this:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">struct User {
username: &amp;str,
email: &amp;str,
sign_in_count: u64,
active: bool,
}
fn main() {
let user1 = User {
email: &quot;someone@example.com&quot;,
username: &quot;someusername123&quot;,
active: true,
sign_in_count: 1,
};
}
</code></pre>
<p>The compiler will complain that it needs lifetime specifiers:</p>
<pre><code class="language-text">error[E0106]: missing lifetime specifier
--&gt;
|
2 | username: &amp;str,
| ^ expected lifetime parameter
error[E0106]: missing lifetime specifier
--&gt;
|
3 | email: &amp;str,
| ^ expected lifetime parameter
</code></pre>
<p>We will talk about how to fix these errors in order to store references in
structs in Chapter 10, but for now, fix errors like these by switching to owned
types like <code>String</code> instead of references like <code>&amp;str</code>.</p>
<h2>An Example Program</h2>
<p>To understand when we might want to use structs, let’s write a program that
calculates the area of a rectangle. We’ll start off with single variables, then
refactor our program until we’re using structs instead.</p>
<p>Let’s make a new binary project with Cargo called <em>rectangles</em> that will take
the length and width of a rectangle specified in pixels and will calculate the
area of the rectangle. Listing 5-2 has a short program with one way of doing
just that in our project’s <em>src/main.rs</em>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let length1 = 50;
let width1 = 30;
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
area(length1, width1)
);
}
fn area(length: u32, width: u32) -&gt; u32 {
length * width
}
</code></pre>
<figcaption>
<p>Listing 5-2: Calculating the area of a rectangle specified by its length and
width in separate variables</p>
</figcaption>
</figure>
<p>Let’s try running this program with <code>cargo run</code>:</p>
<pre><code class="language-text">The area of the rectangle is 1500 square pixels.
</code></pre>
<h3>Refactoring with Tuples</h3>
<p>Our little program works okay; it figures out the area of the rectangle by
calling the <code>area</code> function with each dimension. But we can do better. The
length and the width are related to each other since together they describe one
rectangle.</p>
<p>The issue with this method is evident in the signature of <code>area</code>:</p>
<pre><code class="language-rust,ignore">fn area(length: u32, width: u32) -&gt; u32 {
</code></pre>
<p>The <code>area</code> function is supposed to calculate the area of one rectangle, but our
function has two parameters. The parameters are related, but that’s not
expressed anywhere in our program itself. It would be more readable and more
manageable to group length and width together.</p>
<p>We’ve already discussed one way we might do that in Chapter 3: tuples. Listing
5-3 has a version of our program which uses tuples:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let rect1 = (50, 30);
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
area(rect1)
);
}
fn area(dimensions: (u32, u32)) -&gt; u32 {
dimensions.0 * dimensions.1
}
</code></pre>
<figcaption>
<p>Listing 5-3: Specifying the length and width of the rectangle with a tuple</p>
</figcaption>
</figure>
<!-- I will add ghosting & wingdings once we're in libreoffice /Carol -->
<p>In one way, this is a little better. Tuples let us add a bit of structure, and
we’re now passing just one argument when we call <code>area</code>. But in another way
this method less clear: tuples don’t give names to their elements, so our
calculation has gotten more confusing because we have to index into the parts
of the tuple:</p>
<!-- I will change this to use wingdings instead of repeating this code once
we're in libreoffice /Carol -->
<pre><code class="language-rust,ignore">dimensions.0 * dimensions.1
</code></pre>
<p>It doesn’t matter if we mix up length and width for the area calculation, but
if we were to draw the rectangle on the screen it would matter! We would have
to remember that <code>length</code> was the tuple index <code>0</code> and <code>width</code> was the tuple
index <code>1</code>. If someone else was to work on this code, they would have to figure
this out and remember it as well. It would be easy to forget or mix these
values up and cause errors, since we haven’t conveyed the meaning of our data
in our code.</p>
<h3>Refactoring with Structs: Adding More Meaning</h3>
<p>Here is where we bring in structs. We can transform our tuple into a data type
with a name for the whole as well as names for the parts, as shown in Listing
5-4:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">struct Rectangle {
length: u32,
width: u32,
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
area(&amp;rect1)
);
}
fn area(rectangle: &amp;Rectangle) -&gt; u32 {
rectangle.length * rectangle.width
}
</code></pre>
<figcaption>
<p>Listing 5-4: Defining a <code>Rectangle</code> struct</p>
</figcaption>
</figure>
<!-- Will add ghosting & wingdings once we're in libreoffice /Carol -->
<p>Here we’ve defined a struct and given it the name <code>Rectangle</code>. Inside the <code>{}</code>
we defined the fields to be <code>length</code> and <code>width</code>, both of which have type
<code>u32</code>. Then in <code>main</code>, we create a particular instance of a <code>Rectangle</code> that
has a length of 50 and a width of 30.</p>
<p>Our <code>area</code> function is now defined with one parameter that we’ve named
<code>rectangle</code> whose type is an immutable borrow of a struct <code>Rectangle</code> instance.
As we covered in Chapter 4, we want to borrow the struct rather than take
ownership of it so that <code>main</code> keeps its ownership and can continue using
<code>rect1</code>, so that’s why we have the <code>&amp;</code> in the function signature and at the
call site.</p>
<p>The <code>area</code> function accesses the <code>length</code> and <code>width</code> fields of the
<code>Rectangle</code>. Our function signature for <code>area</code> now says exactly what we mean:
calculate the area of a <code>Rectangle</code>, using its <code>length</code> and <code>width</code> fields.
This conveys that the length and width are related to each other, and gives
descriptive names to the values rather than using the tuple index values of <code>0</code>
and <code>1</code>. This is a win for clarity.</p>
<h3>Adding Useful Functionality with Derived Traits</h3>
<p>It’d be nice to be able to print out an instance of our <code>Rectangle</code> while we’re
debugging our program and see the values for all its fields. Listing 5-5 tries
using the <code>println!</code> macro as we have been:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">struct Rectangle {
length: u32,
width: u32,
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(&quot;rect1 is {}&quot;, rect1);
}
</code></pre>
<figcaption>
<p>Listing 5-5: Attempting to print a <code>Rectangle</code> instance</p>
</figcaption>
</figure>
<p>If we run this, we get an error with this core message:</p>
<pre><code class="language-text">error[E0277]: the trait bound `Rectangle: std::fmt::Display` is not satisfied
</code></pre>
<p>The <code>println!</code> macro can do many kinds of formatting, and by default, <code>{}</code>
tells <code>println!</code> to use formatting known as <code>Display</code>: output intended for
direct end-user consumption. The primitive types we’ve seen so far implement
<code>Display</code> by default, as there’s only one way you’d want to show a <code>1</code> or any
other primitive type to a user. But with structs, the way <code>println!</code> should
format the output is less clear as there are more display possibilities: Do you
want commas or not? Do you want to print the struct <code>{}</code>s? Should all the
fields be shown? Because of this ambiguity, Rust doesn’t try to guess what we
want and structs do not have a provided implementation of <code>Display</code>.</p>
<p>If we keep reading the errors, though, we’ll find this helpful note:</p>
<pre><code class="language-text">note: `Rectangle` cannot be formatted with the default formatter; try using
`:?` instead if you are using a format string
</code></pre>
<p>Let’s try it! The <code>println!</code> will now look like
<code>println!(&quot;rect1 is {:?}&quot;, rect1);</code>. Putting the specifier <code>:?</code> inside
the <code>{}</code> tells <code>println!</code> we want to use an output format called <code>Debug</code>.
<code>Debug</code> is a trait that enables us to print out our struct in a way that is
useful for developers so that we can see its value while we are debugging our
code.</p>
<p>Let’s try running with this change and… drat. We still get an error:</p>
<pre><code class="language-text">error: the trait bound `Rectangle: std::fmt::Debug` is not satisfied
</code></pre>
<p>Again, though, the compiler has given us a helpful note!</p>
<pre><code class="language-text">note: `Rectangle` cannot be formatted using `:?`; if it is defined in your
crate, add `#[derive(Debug)]` or manually implement it
</code></pre>
<p>Rust <em>does</em> include functionality to print out debugging information, but we
have to explicitly opt-in to having that functionality be available for our
struct. To do that, we add the annotation <code>#[derive(Debug)]</code> just before our
struct definition, as shown in Listing 5-6:</p>
<figure>
<pre><code class="language-rust">#[derive(Debug)]
struct Rectangle {
length: u32,
width: u32,
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(&quot;rect1 is {:?}&quot;, rect1);
}
</code></pre>
<figcaption>
<p>Listing 5-6: Adding the annotation to derive the <code>Debug</code> trait and printing the
<code>Rectangle</code> instance using debug formatting</p>
</figcaption>
</figure>
<p>At this point, if we run this program, we won’t get any errors and we’ll see
the following output:</p>
<pre><code class="language-text">rect1 is Rectangle { length: 50, width: 30 }
</code></pre>
<p>Nice! It’s not the prettiest output, but it shows the values of all the fields
for this instance, which would definitely help during debugging. If we want
output that is a bit prettier and easier to read, which can be helpful with
larger structs, we can use <code>{:#?}</code> in place of <code>{:?}</code> in the <code>println!</code> string.
If we use the pretty debug style in this example, the output will look like:</p>
<pre><code class="language-text">rect1 is Rectangle {
length: 50,
width: 30
}
</code></pre>
<p>There are a number of traits Rust has provided for us to use with the <code>derive</code>
annotation that can add useful behavior to our custom types. Those traits and
their behaviors are listed in Appendix C. We’ll be covering how to implement
these traits with custom behavior, as well as creating your own traits, in
Chapter 10.</p>
<p>Our <code>area</code> function is pretty specific—it only computes the area of rectangles.
It would be nice to tie this behavior together more closely with our
<code>Rectangle</code> struct, since it’s behavior that our <code>Rectangle</code> type has
specifically. Let’s now look at how we can continue to refactor this code by
turning the <code>area</code> function into an <code>area</code> <em>method</em> defined on our <code>Rectangle</code>
type.</p>
</div>
<!-- Mobile navigation buttons -->
<a href="ch04-03-slices.html" class="mobile-nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="ch05-01-method-syntax.html" class="mobile-nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<a href="ch04-03-slices.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="ch05-01-method-syntax.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>
<!-- Livereload script (if served using the cli tool) -->
<script src="highlight.js"></script>
<script src="book.js"></script>
</body>
</html>