Files
book/ch05-00-structs.html
T

356 lines
23 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Rust Programming Language</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="">
<link rel="stylesheet" href="book.css">
<link href='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-in-rust.html"><strong>3.</strong> Common Programming Concepts in Rust</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-ownership.html"><strong>4.1.</strong> 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><strong>10.</strong> Generics</li><li><strong>11.</strong> I/O</li><li><ul class="section"><li><strong>11.1.</strong> <code>Read</code> &amp; <code>Write</code></li><li><strong>11.2.</strong> <code>std::fs</code></li><li><strong>11.3.</strong> <code>std::path</code></li><li><strong>11.4.</strong> <code>std::env</code></li></ul></li><li><strong>12.</strong> Testing</li><li><ul class="section"><li><strong>12.1.</strong> Unit Tests</li><li><strong>12.2.</strong> Integration Tests</li><li><strong>12.3.</strong> Test Attribute</li></ul></li><li><strong>13.</strong> Composition</li><li><ul class="section"><li><strong>13.1.</strong> Instead of Inheritance</li><li><strong>13.2.</strong> Trait Objects?</li></ul></li><li><strong>14.</strong> Creating a Library</li><li><ul class="section"><li><strong>14.1.</strong> Cargo</li><li><strong>14.2.</strong> Crates.io</li><li><a href="chYY-YY-public-api.html"><strong>14.3.</strong> Organizing your Public API</a></li><li><a href="chYY-YY-documentation.html"><strong>14.4.</strong> Documentation</a></li><li><a href="chYY-YY-workspaces.html"><strong>14.5.</strong> Workspaces and Multiple Related Crates</a></li></ul></li><li><strong>15.</strong> Closures</li><li><strong>16.</strong> Zero-cost Abstractions</li><li><ul class="section"><li><strong>16.1.</strong> Iterators as a Case Study</li></ul></li><li><strong>17.</strong> Smart Pointers</li><li><ul class="section"><li><strong>17.1.</strong> <code>Box&lt;T&gt;</code></li><li><strong>17.2.</strong> <code>Rc&lt;T&gt;</code></li><li><strong>17.3.</strong> <code>Cell</code></li><li><strong>17.4.</strong> <code>RefCell</code></li><li><strong>17.5.</strong> Interior Mutability</li></ul></li><li><strong>18.</strong> Concurrency</li><li><ul class="section"><li><strong>18.1.</strong> Threads</li><li><strong>18.2.</strong> <code>Send</code> &amp; <code>Sync</code></li><li><strong>18.3.</strong> <code>Arc&lt;T&gt;</code></li><li><strong>18.4.</strong> <code>Mutex&lt;T&gt;</code></li><li><strong>18.5.</strong> <code>Channels</code></li></ul></li><li><a href="chXX-patterns.html"><strong>19.</strong> Patterns</a></li><li><strong>20.</strong> More Lifetimes</li><li><strong>21.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>21.1.</strong> Raw Pointers</li><li><strong>21.2.</strong> <code>transmute</code></li></ul></li><li><strong>22.</strong> Foreign Function Interface</li><li><ul class="section"><li><strong>22.1.</strong> Conditional Compilation</li><li><strong>22.2.</strong> Bindings to C</li><li><strong>22.3.</strong> Using Rust from Other Languages</li><li><strong>22.4.</strong> <code>static</code></li></ul></li><li><strong>23.</strong> Advanced Type System Features</li><li><ul class="section"><li><strong>23.1.</strong> Associated Types</li><li><strong>23.2.</strong> Trait Objects</li><li><strong>23.3.</strong> UFCS</li><li><strong>23.4.</strong> Coherence</li></ul></li><li><strong>24.</strong> Macros</li><li><ul class="section"><li><strong>24.1.</strong> Writing Your Own Macros</li></ul></li><li><strong>25.</strong> Nightly Rust</li><li><ul class="section"><li><strong>25.1.</strong> Nightly Features</li><li><strong>25.2.</strong> How to Find Out About Nightly Features</li></ul></li><li><a href="appendix-00.html"><strong>26.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>26.1.</strong> Keywords</a></li><li><a href="appendix-02-operators.html"><strong>26.2.</strong> Operators</a></li><li><a href="appendix-03-derivable-traits.html"><strong>26.3.</strong> Derivable Traits</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 that 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, a struct to store information about a user account might look like:</p>
<pre><code class="language-rust">struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
</code></pre>
<p>To use a struct, we create an <em>instance</em> of that struct by specifying concrete
values for each of the fields. Creating an instance is done by declaring a
variable with <code>let</code>, 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>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 <code>struct</code>s 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. Here’s a short program that has one way of doing just
that to put into our project's <code>src/main.rs</code>:</p>
<p>Filename: src/main.rs</p>
<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>
<p>Let's try running this program with <code>cargo run</code>:</p>
<pre><code class="language-bash">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 area function is supposed to calculate the area of one rectangle, but our
function takes two arguments. The arguments 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. Here’s a
version of our program which uses tuples:</p>
<p>Filename: src/main.rs</p>
<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>
<!-- 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. 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 <code>struct</code>s. We can transform our tuple into a data
type with a name for the whole as well as names for the parts:</p>
<p>Filename: src/main.rs</p>
<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>
<!-- Will add ghosting & wingdings once we're in libreoffice /Carol -->
<p>Here we've defined a <code>struct</code> 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 now takes one argument 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>
instance it got as an argument. 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. Let's try using
the <code>println!</code> macro as we have been and see what happens:</p>
<p>Filename: src/main.rs</p>
<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>
<p>If we run this, we get an error with this core message:</p>
<pre><code class="language-bash">error: 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-bash">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-bash">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-bash">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. Now our program looks like this:</p>
<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>
<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-bash">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.</p>
<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 XX. 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>