mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:34:52 -06:00
rebuild pages at 091e1bc
This commit is contained in:
+194
-196
@@ -68,246 +68,244 @@
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Structs</h1>
|
||||
<p>A <code>struct</code>, short for "structure", gives us the ability to 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. <code>struct</code> and <code>enum</code> (that we will talk about in the next chapter)
|
||||
are the building blocks you can use in Rust to create new types in your
|
||||
<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>Let’s write a program which calculates the distance between two points.
|
||||
We’ll start off with single variable bindings, and then refactor it to
|
||||
use <code>struct</code>s instead.</p>
|
||||
<p>Let’s make a new project with Cargo called <code>points</code>. Here’s a short program
|
||||
which calculates the distance between two points to put into this project's
|
||||
<code>src/main.rs</code>:</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
|
||||
binding 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("someone@example.com"),
|
||||
username: String::from("someusername123"),
|
||||
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 variable
|
||||
bindings, 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 x1 = 0.0;
|
||||
let y1 = 5.0;
|
||||
let length1 = 50;
|
||||
let width1 = 30;
|
||||
|
||||
let x2 = 12.0;
|
||||
let y2 = 0.0;
|
||||
|
||||
let answer = distance(x1, y1, x2, y2);
|
||||
|
||||
println!("Point 1: ({}, {})", x1, y1);
|
||||
println!("Point 2: ({}, {})", x2, y2);
|
||||
println!("Distance: {}", answer);
|
||||
println!(
|
||||
"The area of the rectangle is {} square pixels.",
|
||||
area(length1, width1)
|
||||
);
|
||||
}
|
||||
|
||||
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
|
||||
let x_squared = f64::powi(x2 - x1, 2);
|
||||
let y_squared = f64::powi(y2 - y1, 2);
|
||||
|
||||
f64::sqrt(x_squared + y_squared)
|
||||
fn area(length: u32, width: u32) -> u32 {
|
||||
length * width
|
||||
}
|
||||
</code></pre>
|
||||
<p>Let's try running this program with <code>cargo run</code>:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling points v0.1.0 (file:///projects/points)
|
||||
Running `target/debug/points`
|
||||
Point 1: (0, 5)
|
||||
Point 2: (12, 0)
|
||||
Distance: 13
|
||||
<pre><code class="language-bash">The area of the rectangle is 1500 square pixels.
|
||||
</code></pre>
|
||||
<p>Let's take a quick look at <code>distance()</code> before we move forward. To find the
|
||||
distance between two points, we can use the Pythagorean Theorem. The theorem is
|
||||
named after Pythagoras, who was the first person to mathematically prove this
|
||||
formula. The details aren't that important; just know the theorem says that the
|
||||
formula for the distance between two points is equal to:</p>
|
||||
<ul>
|
||||
<li>squaring the distance between the points horizontally (the "x" direction)</li>
|
||||
<li>squaring the distance between the points vertically (the "y" direction)</li>
|
||||
<li>adding those together</li>
|
||||
<li>and taking the square root of that.</li>
|
||||
</ul>
|
||||
<p>So that's what we're implementing here.</p>
|
||||
<pre><code class="language-rust,ignore">f64::powi(2.0, 3)
|
||||
<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) -> u32 {
|
||||
</code></pre>
|
||||
<p>The double colon (<code>::</code>) here is a namespace operator. We haven’t talked about
|
||||
modules and namespaces in depth yet, but you can think of the <code>powi()</code> function
|
||||
as being scoped inside of another name. In this case, the name is <code>f64</code>, the
|
||||
same as the type. The <code>powi()</code> function takes two arguments: the first is a
|
||||
number, and the second is the power that it raises that number to. In this
|
||||
case, the second number is an integer, hence the <code>i</code> in its name. Similarly,
|
||||
<code>sqrt()</code> is a function under the <code>f64</code> module, which takes the square root of
|
||||
its argument.</p>
|
||||
<h2>Why <code>struct</code>s?</h2>
|
||||
<p>Our little program is okay, but we can do better. The key to seeing this is in
|
||||
the signature of <code>distance()</code>:</p>
|
||||
<pre><code class="language-rust,ignore">fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
|
||||
</code></pre>
|
||||
<p>The distance function is supposed to calculate the distance between two points.
|
||||
But our distance function calculates some distance between four numbers. The
|
||||
first two and last two arguments are related, but that’s not expressed anywhere
|
||||
in our program itself. It would be nicer if we had a way to group <code>(x1, y1)</code>
|
||||
and <code>(x2, y2)</code> together.</p>
|
||||
<p>We’ve already discussed one way to do that: tuples. Here’s a version of our
|
||||
program which uses tuples:</p>
|
||||
<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 p1 = (0.0, 5.0);
|
||||
let rect1 = (50, 30);
|
||||
|
||||
let p2 = (12.0, 0.0);
|
||||
|
||||
let answer = distance(p1, p2);
|
||||
|
||||
println!("Point 1: {:?}", p1);
|
||||
println!("Point 2: {:?}", p2);
|
||||
println!("Distance: {}", answer);
|
||||
println!(
|
||||
"The area of the rectangle is {} square pixels.",
|
||||
area(rect1)
|
||||
);
|
||||
}
|
||||
|
||||
fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 {
|
||||
let x_squared = f64::powi(p2.0 - p1.0, 2);
|
||||
let y_squared = f64::powi(p2.1 - p1.1, 2);
|
||||
|
||||
f64::sqrt(x_squared + y_squared)
|
||||
fn area(dimensions: (u32, u32)) -> u32 {
|
||||
dimensions.0 * dimensions.1
|
||||
}
|
||||
</code></pre>
|
||||
<p>This is a little better, for sure. Tuples let us add a little bit of structure.
|
||||
We’re now passing two arguments, so that’s more clear. But it’s also worse:
|
||||
<!-- 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:</p>
|
||||
<pre><code class="language-rust,ignore">p2.0 - p1.0
|
||||
p2.1 - p1.1
|
||||
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>When writing this example, your authors almost got it wrong themselves! Distance
|
||||
is all about <code>x</code> and <code>y</code> points, but our code is talking about <code>0</code> and <code>1</code>.
|
||||
This isn’t great.</p>
|
||||
<p>Enter <code>struct</code>s. We can transform our tuples into something with a name for the
|
||||
whole as well as names for the parts:</p>
|
||||
<pre><code class="language-rust,ignore">let p1 = (0.0, 5.0);
|
||||
|
||||
struct Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
}
|
||||
|
||||
let p1 = Point { x: 0.0, y: 5.0 };
|
||||
</code></pre>
|
||||
<p>Here we've defined a <code>struct</code> and given it the name <code>Point</code>. The parts inside
|
||||
<code>{}</code> are defining the <em>fields</em> of the struct. We can have as many or as few of
|
||||
them as we'd like, and we give them a name and specify their type. Here we have
|
||||
two fields named <code>x</code> and <code>y</code>, and they both hold <code>f64</code>s.</p>
|
||||
<p>We can access the field of a struct in the same way we access an element of
|
||||
a tuple, except we use its name:</p>
|
||||
<pre><code class="language-rust,ignore">let p1 = (0.0, 5.0);
|
||||
let x = p1.0;
|
||||
|
||||
struct Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
}
|
||||
|
||||
let p1 = Point { x: 0.0, y: 5.0 };
|
||||
let x = p1.x;
|
||||
</code></pre>
|
||||
<p>Let’s convert our program to use our <code>Point</code> <code>struct</code>. Here’s what it looks
|
||||
like now:</p>
|
||||
<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">#[derive(Debug,Copy,Clone)]
|
||||
struct Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
<pre><code class="language-rust">struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let p1 = Point { x: 0.0, y: 5.0};
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
|
||||
let p2 = Point { x: 12.0, y: 0.0};
|
||||
|
||||
let answer = distance(p1, p2);
|
||||
|
||||
println!("Point 1: {:?}", p1);
|
||||
println!("Point 2: {:?}", p2);
|
||||
println!("Distance: {}", answer);
|
||||
println!(
|
||||
"The area of the rectangle is {} square pixels.",
|
||||
area(&rect1)
|
||||
);
|
||||
}
|
||||
|
||||
fn distance(p1: Point, p2: Point) -> f64 {
|
||||
let x_squared = f64::powi(p2.x - p1.x, 2);
|
||||
let y_squared = f64::powi(p2.y - p1.y, 2);
|
||||
|
||||
f64::sqrt(x_squared + y_squared)
|
||||
fn area(rectangle: &Rectangle) -> u32 {
|
||||
rectangle.length * rectangle.width
|
||||
}
|
||||
</code></pre>
|
||||
<p>Our function signature for <code>distance()</code> now says exactly what we mean: it
|
||||
calculates the distance between two <code>Point</code>s. And rather than <code>0</code> and <code>1</code>,
|
||||
we’ve got back our <code>x</code> and <code>y</code>. This is a win for clarity.</p>
|
||||
<h2>Derived Traits</h2>
|
||||
<p>There’s one other thing that’s a bit strange here, this stuff above the
|
||||
<code>struct</code> declaration:</p>
|
||||
<pre><code class="language-rust,ignore">#[derive(Debug,Copy,Clone)]
|
||||
struct Point {
|
||||
</code></pre>
|
||||
<p>This is an annotation that tells the compiler our struct should get some
|
||||
default behavior for the <code>Debug</code>, <code>Copy</code>, and <code>Clone</code> traits. We talked about
|
||||
marking that types can be <code>Copy</code> and <code>Clone</code>-able in Chapter XX when we
|
||||
discussed ownership. <code>Debug</code> is the trait that enables us to print out our
|
||||
struct so that we can see its value while we are debugging our code.</p>
|
||||
<p>So far, we’ve been printing values using <code>{}</code> in a <code>println!</code> macro. If we try
|
||||
that with a struct, however, by default, we'll get an error. Say we have the
|
||||
following program:</p>
|
||||
<!-- 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>&</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 Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
<pre><code class="language-rust,ignore">struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let p1 = Point { x: 0.0, y: 5.0};
|
||||
println!("Point 1: {}", p1);
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
|
||||
println!("rect1 is {}", rect1);
|
||||
}
|
||||
</code></pre>
|
||||
<p>This code tries to print the <code>p1</code> point directly, which may seem innocuous. But
|
||||
running it produces the following output:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling points v0.1.0 (file:///projects/points)
|
||||
error: the trait bound `Point: std::fmt::Display` is not satisfied [--explain E0277]
|
||||
--> src/main.rs:8:29
|
||||
8 |> println!("Point 1: {}", p1);
|
||||
|> ^^
|
||||
<std macros>:2:27: 2:58: note: in this expansion of format_args!
|
||||
<std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>)
|
||||
src/main.rs:8:5: 8:33: note: in this expansion of println! (defined in <std macros>)
|
||||
note: `Point` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
|
||||
note: required by `std::fmt::Display::fmt`
|
||||
<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>Whew! The core of the error is this part: <em>the trait bound <code>Point: std::fmt::Display</code> is not satisfied</em>. <code>println!</code> can do many kinds of
|
||||
formatting. By default, <code>{}</code> implements a kind of formatting known as
|
||||
<code>Display</code>: output intended for direct end-user consumption. The primitive types
|
||||
we’ve seen implement <code>Display</code>, as there’s only one way you’d show a <code>1</code> to a
|
||||
user. But with structs, the output is less clear. Do you want commas or not?
|
||||
What about the <code>{}</code>s? Should all the fields be shown?</p>
|
||||
<p>More complex types in the standard library and that are defined by the
|
||||
programmer do not automatically implement <code>Display</code> formatting. Standard
|
||||
library types implement <code>Debug</code> formatting, which is intended for the
|
||||
programmer to see. The <code>#[derive(Debug)]</code> annotation lets us use a default
|
||||
implementation of <code>Debug</code> formatting to easily get this ability for types we've
|
||||
defined. To ask <code>println!</code> to use <code>Debug</code> formatting with our <code>Point</code>, we add
|
||||
the annotation to derive the trait and include <code>:?</code> in the print string, like
|
||||
this:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<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!("rect1 is {:?}", 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 compliler 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 Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let p1 = Point { x: 0.0, y: 5.0};
|
||||
println!("Point 1: {:?}", p1);
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
|
||||
println!("rect1 is {:?}", rect1);
|
||||
}
|
||||
</code></pre>
|
||||
<p>If you run this, it should print the values of each field in the <code>Point</code> struct
|
||||
as desired:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling points v0.1.0 (file:///projects/points)
|
||||
Running `target/debug/points`
|
||||
Point 1: Point { x: 0, y: 5 }
|
||||
<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>You’ll see this repeated later with other types. We’ll cover traits fully in
|
||||
Chapter XX.</p>
|
||||
<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>
|
||||
|
||||
|
||||
+154
-110
@@ -68,108 +68,77 @@
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Method Syntax</h2>
|
||||
<p>In Chapter 4 when we discussed ownership, we made several references to
|
||||
<em>methods</em>. Methods look like this:</p>
|
||||
<pre><code class="language-rust">let s1 = "hello";
|
||||
|
||||
// call a method on s1
|
||||
let s2 = s1.clone();
|
||||
|
||||
println!("{}", s1);
|
||||
</code></pre>
|
||||
<p>The call to <code>clone()</code> is attached to <code>s1</code> with a dot. This is called <em>method
|
||||
syntax</em>, and it’s a way to call certain functions with a different style.</p>
|
||||
<p>Why have two ways to call functions? We’ll talk about some deeper reasons
|
||||
related to ownership in a moment, but one big reason is that methods look nicer
|
||||
when chained together:</p>
|
||||
<pre><code class="language-rust,ignore">// with functions
|
||||
h(g(f(x)));
|
||||
|
||||
// with methods
|
||||
x.f().g().h();
|
||||
</code></pre>
|
||||
<p>The nested-functions version reads in reverse: the program executes <code>f()</code>, then
|
||||
<code>g()</code>, then <code>h()</code>, but we read it left-to-right as <code>h()</code>, then <code>g()</code>, then
|
||||
<code>f()</code>. The method syntax is executed in the same order as we would read it.</p>
|
||||
<p>Before we get into the details, let’s talk about how to define your own
|
||||
methods.</p>
|
||||
<h3>Defining methods</h3>
|
||||
<p>We can define methods with the <code>impl</code> keyword. <code>impl</code> is short for
|
||||
<em>implementation</em>. Doing so looks like this:</p>
|
||||
<pre><code class="language-rust">#[derive(Debug,Copy,Clone)]
|
||||
struct Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
<p><em>Methods</em> are similar to functions: they're declared with the <code>fn</code> keyword and
|
||||
their name, they can take arguments and return values, and they contain some
|
||||
code that gets run when they're called from somewhere else. Methods are
|
||||
different from functions, however, because they're defined within the context
|
||||
of a struct (or an enum or a trait object, which we will cover in Chapters 6
|
||||
and XX respectively), and their first argument is always <code>self</code>, which
|
||||
represents the instance of the struct that the method is being called on.</p>
|
||||
<h3>Defining Methods</h3>
|
||||
<p>Let's change our <code>area</code> function that takes a <code>Rectangle</code> instance as an
|
||||
argument and instead make an <code>area</code> method defined on the <code>Rectangle</code> struct:</p>
|
||||
<pre><code class="language-rust">#[derive(Debug)]
|
||||
struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
impl Point {
|
||||
fn distance(&self, other: &Point) -> f64 {
|
||||
let x_squared = f64::powi(other.x - self.x, 2);
|
||||
let y_squared = f64::powi(other.y - self.y, 2);
|
||||
|
||||
f64::sqrt(x_squared + y_squared)
|
||||
impl Rectangle {
|
||||
fn area(&self) -> u32 {
|
||||
self.length * self.width
|
||||
}
|
||||
}
|
||||
|
||||
let p1 = Point { x: 0.0, y: 0.0 };
|
||||
let p2 = Point { x: 5.0, y: 6.5 };
|
||||
fn main() {
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
|
||||
assert_eq!(8.200609733428363, p1.distance(&p2));
|
||||
</code></pre>
|
||||
<p>Let’s break this down. First, we have our <code>Point</code> struct from earlier in the
|
||||
chapter. Next comes our first use of the <code>impl</code> keyword:</p>
|
||||
<pre><code class="language-rust,ignore">impl Point {
|
||||
// ...
|
||||
println!(
|
||||
"The area of the rectangle is {} square pixels.",
|
||||
rect1.area()
|
||||
);
|
||||
}
|
||||
</code></pre>
|
||||
<p>Everything we put inside of the curly braces will be methods implemented on
|
||||
<code>Point</code>. Next is our definition:</p>
|
||||
<pre><code class="language-rust,ignore">fn distance(&self, other: &Point) -> f64 {
|
||||
// ...
|
||||
}
|
||||
</code></pre>
|
||||
<p>Other than this, the rest of the example is familiar: an implementation of
|
||||
<code>distance()</code> and using the method to find an answer.</p>
|
||||
<p>Our definition of <code>distance()</code> here as a method looks very similar to our
|
||||
previous definition of <code>distance()</code> as a function, but with two differences.
|
||||
Here's the <code>distance()</code> function again:</p>
|
||||
<pre><code class="language-rust,ignore">fn distance(p1: Point, p2: Point) -> f64 {
|
||||
// ...
|
||||
}
|
||||
</code></pre>
|
||||
<p>The first difference is in the first argument. Instead of a name and a type, we
|
||||
have written <code>&self</code>. This is what distinguishes a method from a function:
|
||||
using <code>self</code> inside of an <code>impl</code> block means we have a method. Because we
|
||||
already know that we are implementing this method on <code>Point</code> because of the
|
||||
surrounding <code>impl Point</code> block, we don’t need to write the type of <code>self</code> out.</p>
|
||||
<p>Note that we have written <code>&self</code>, not just <code>self</code>. This is because we want to
|
||||
take a reference to our argument's value rather than taking ownership of it. In
|
||||
other words, these two forms are the same:</p>
|
||||
<pre><code class="language-rust,ignore">fn foo(self: &Point)
|
||||
fn foo(&self)
|
||||
</code></pre>
|
||||
<p>Just like any other parameter, you can take <code>self</code> in three forms. Here’s the
|
||||
list, with the most common form first:</p>
|
||||
<pre><code class="language-rust,ignore">fn foo(&self) // take self by reference
|
||||
fn foo(&mut self) // take self by mutable reference
|
||||
fn foo(self) // take self by ownership
|
||||
</code></pre>
|
||||
<p>In this case, we only need a reference. We don’t need to mutate either <code>Point</code>
|
||||
to get the distance between them, so we won't take a mutable reference to the
|
||||
<code>Point</code> that we call the method on. Methods that take ownership of <code>self</code> are
|
||||
rarely used. An example of a time to do that would be if we wanted to have a
|
||||
method that would transform <code>self</code> into something else and prevent other code
|
||||
from using the value of <code>self</code> after the transformation happens.</p>
|
||||
<h4>Methods and automatic referencing</h4>
|
||||
<p>We’ve left out an important detail. It’s in this line of the example:</p>
|
||||
<pre><code class="language-rust,ignore">assert_eq!(8.200609733428363, p1.distance(&p2));
|
||||
</code></pre>
|
||||
<p>When we defined <code>distance()</code>, we took both <code>self</code> and the other argument by
|
||||
reference. Yet, we needed a <code>&</code> for <code>p2</code> but not <code>p1</code>. What gives?</p>
|
||||
<p>This feature is called <em>automatic referencing</em>, and calling methods is one
|
||||
of the few places in Rust that has behavior like this. Here’s how it works:
|
||||
when you call a method with <code>self.(</code>, Rust will automatically add in <code>&</code>s
|
||||
or <code>&mut</code>s to match the signature. In other words, these are the same:</p>
|
||||
<!-- Will add ghosting and wingdings here in libreoffice /Carol -->
|
||||
<p>In order to make the function be defined within the context of <code>Rectangle</code>, we
|
||||
start an <code>impl</code> block (<code>impl</code> is short for <em>implementation</em>). Then we move the
|
||||
function within the <code>impl</code> curly braces, and change the first (and in this
|
||||
case, only) argument to be <code>self</code> in the signature and everywhere within the
|
||||
body. Then in <code>main</code> where we called the <code>area</code> function and passed <code>rect1</code> as
|
||||
an argument, we can instead use <em>method syntax</em> to call the <code>area</code> method on
|
||||
our <code>Rectangle</code> instance.</p>
|
||||
<p>In the signature for <code>area</code>, we get to use <code>&self</code> instead of <code>rectangle: &Rectangle</code> because Rust knows the type of <code>self</code> is <code>Rectangle</code> due to this
|
||||
method being inside the <code>impl Rectangle</code> context. Note we still need to have
|
||||
the <code>&</code> before <code>self</code>, just like we had <code>&Rectangle</code>. Methods can choose to
|
||||
take ownership of <code>self</code>, borrow <code>self</code> immutably as we've done here, or borrow
|
||||
<code>self</code> mutably, just like any other argument.</p>
|
||||
<p>We've chosen <code>&self</code> here for the same reason we used <code>&Rectangle</code> in the
|
||||
function version: we don't want to take ownership, and we just want to be able
|
||||
to read the data in the struct, not write to it. If we wanted to be able to
|
||||
change the instance that we've called the method on as part of what the method
|
||||
does, we'd put <code>&mut self</code> as the first argument instead. Having a method that
|
||||
takes ownership of the instance by having just <code>self</code> as the first argument is
|
||||
rarer; this is usually used when the method transforms <code>self</code> into something
|
||||
else and we want to prevent the caller from using the original instance after
|
||||
the transformation.</p>
|
||||
<p>The main benefit of using methods over functions, in addition to getting to use
|
||||
method syntax and not having to repeat the type of <code>self</code> in every method's
|
||||
signature, is for organization. We've put all the things we can do with an
|
||||
instance of a type together in one <code>impl</code> block, rather than make future users
|
||||
of our code search for capabilities of <code>Rectangle</code> all over the place.</p>
|
||||
<!-- PROD: START BOX -->
|
||||
<h4>Where's the <code>-></code> operator?</h4>
|
||||
<p>In languages like C++, there are two different operators for calling methods:
|
||||
<code>.</code> if you're calling a method on the object directly, and <code>-></code> if you're
|
||||
calling the method on a pointer to the object and thus need to dereference the
|
||||
pointer first. In other words, if <code>object</code> is a pointer, <code>object->something()</code>
|
||||
is like <code>(*object).something()</code>.</p>
|
||||
<p>Rust doesn't have an equivalent to the <code>-></code> operator; instead, Rust has a
|
||||
feature called <em>automatic referencing and dereferencing</em>. Calling methods is
|
||||
one of the few places in Rust that has behavior like this.</p>
|
||||
<p>Here’s how it works: when you call a method with <code>object.something()</code>, Rust
|
||||
will automatically add in <code>&</code>, <code>&mut</code>, or <code>*</code> so that <code>object</code> matches the
|
||||
signature of the method. In other words, these are the same:</p>
|
||||
<pre><code class="language-rust"># #[derive(Debug,Copy,Clone)]
|
||||
# struct Point {
|
||||
# x: f64,
|
||||
@@ -189,25 +158,100 @@ or <code>&mut</code>s to match the signature. In other words, these are the
|
||||
p1.distance(&p2);
|
||||
(&p1).distance(&p2);
|
||||
</code></pre>
|
||||
<p>The first one looks much, much cleaner. Here’s another example:</p>
|
||||
<pre><code class="language-rust">let mut s = String::from("Hello,");
|
||||
<p>The first one looks much, much cleaner. This automatic referencing behavior
|
||||
works because methods have a clear receiver — the type of <code>self</code>. Given the
|
||||
receiver and name of a method, Rust can figure out definitively whether the
|
||||
method is just reading (so needs <code>&self</code>), mutating (so <code>&mut self</code>), or
|
||||
consuming (so <code>self</code>). The fact that Rust makes borrowing implicit for method
|
||||
receivers is a big part of making ownership ergonomic in practice.</p>
|
||||
<!-- PROD: END BOX -->
|
||||
<h3>Methods with More Arguments</h3>
|
||||
<p>Let's practice some more with methods by implementing a second method on our
|
||||
<code>Rectangle</code> struct. This time, we'd like for an instance of <code>Rectangle</code> to take
|
||||
another instance of <code>Rectangle</code> and return <code>true</code> if the second rectangle could
|
||||
fit completely within <code>self</code> and <code>false</code> if it would not. That is, if we run
|
||||
this code:</p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
let rect2 = Rectangle { length: 40, width: 10 };
|
||||
let rect3 = Rectangle { length: 45, width: 60 };
|
||||
|
||||
s.push_str(" world!");
|
||||
|
||||
// The above is the same as:
|
||||
// (&mut s).push_str(" world!");
|
||||
|
||||
assert_eq!("Hello, world!", s);
|
||||
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
|
||||
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
|
||||
}
|
||||
</code></pre>
|
||||
<p>Because [<code>push_str()</code>][pushstr]<!-- ignore --> has the following signature:</p>
|
||||
<pre><code class="language-rust,ignore">fn push_str(&mut self, string: &str) {
|
||||
<p>We want to see this output, since both of <code>rect2</code>'s dimensions are smaller than
|
||||
<code>rect1</code>'s, but <code>rect3</code> is wider than <code>rect1</code>:</p>
|
||||
<pre><code class="language-bash">Can rect1 hold rect2? true
|
||||
Can rect1 hold rect3? false
|
||||
</code></pre>
|
||||
<p>This automatic referencing behavior works because methods have a clear receiver
|
||||
— the type of <code>self</code> — and in most cases it’s clear given the receiver and name
|
||||
of a method whether the method is just reading (so needs <code>&self</code>), mutating (so
|
||||
<code>&mut self</code>), or consuming (so <code>self</code>). The fact that Rust makes borrowing
|
||||
implicit for method receivers is a big part of making ownership ergonomic in
|
||||
practice.</p>
|
||||
<p>We know we want to define a method, so it will be within the <code>impl Rectangle</code>
|
||||
block. The method name will be <code>can_hold</code>, and it will take an immutable borrow
|
||||
of another <code>Rectangle</code> as an argument. We can tell what the type of the
|
||||
argument will be by looking at a call site: <code>rect1.can_hold(&rect2)</code> passes in
|
||||
<code>&rect2</code>, which is an immutable borrow to <code>rect2</code>, an instance of <code>Rectangle</code>.
|
||||
This makes sense, since we only need to read <code>rect2</code> (rather than write, which
|
||||
would mean we'd need a mutable borrow) and we want <code>main</code> to keep ownership of
|
||||
<code>rect2</code> so that we could use it again after calling this method. The return
|
||||
value of <code>can_hold</code> will be a boolean, and the implementation will check to see
|
||||
if <code>self</code>'s length and width are both greater than the length and width of the
|
||||
other <code>Rectagle</code>, respectively. Let's write that code!</p>
|
||||
<pre><code># #[derive(Debug)]
|
||||
# struct Rectangle {
|
||||
# length: u32,
|
||||
# width: u32,
|
||||
# }
|
||||
#
|
||||
impl Rectangle {
|
||||
fn area(&self) -> u32 {
|
||||
self.length * self.width
|
||||
}
|
||||
|
||||
fn can_hold(&self, other: &Rectangle) -> bool {
|
||||
self.length > other.length && self.width > other.width
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<!-- Will add ghosting here in libreoffice /Carol -->
|
||||
<p>If we run this with the <code>main</code> from earlier, we will get our desired output!
|
||||
Methods can take multiple arguments that we add to the signature after the
|
||||
<code>self</code> parameter, and those arguments work just like arguments in functions do.</p>
|
||||
<h3>Associated Functions</h3>
|
||||
<p>One more useful feature of <code>impl</code> blocks: we're allowed to define functions
|
||||
within <code>impl</code> blocks that <em>don't</em> take <code>self</code> as a parameter. These are called
|
||||
<em>associated functions</em>, since they're associated with the struct. They're still
|
||||
functions though, not methods, since they don't have an instance of the struct
|
||||
to work with. You've already used an associated function: <code>String::from</code>.</p>
|
||||
<p>Associated functions are often used for constructors that will return a new
|
||||
instance of the struct. For example, we could provide an associated function
|
||||
that would take one dimension argument and use that as both length and width,
|
||||
thus making it easier to create a square <code>Rectangle</code> rather than having to
|
||||
specify the same value twice:</p>
|
||||
<pre><code class="language-rust"># #[derive(Debug)]
|
||||
# struct Rectangle {
|
||||
# length: u32,
|
||||
# width: u32,
|
||||
# }
|
||||
#
|
||||
impl Rectangle {
|
||||
fn square(size: u32) -> Rectangle {
|
||||
Rectangle { length: size, width: size }
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<p>To call this associated function, we use the <code>::</code> syntax with the struct name:
|
||||
<code>let sq = Rectange::square(3);</code>, for example. It's kind of this function is
|
||||
namespaced by the struct: the <code>::</code> syntax is used for both associated functions
|
||||
and namespaces created by modules, which we'll learn about in Chapter 7.</p>
|
||||
<h2>Summary</h2>
|
||||
<p>Structs let us create custom types that are meaningful for our domain. By using
|
||||
structs, we can keep associated pieces of data connected to each other and name
|
||||
each piece to make our code clear. Methods let us specify the behavior that
|
||||
instances of our structs have, and associated functions let us namespace
|
||||
functionality that is particular to our struct without having an instance
|
||||
available.</p>
|
||||
<p>Structs aren't the only way we can create custom types, though; let's turn to
|
||||
the <code>enum</code> feature of Rust and add another tool to our toolbox.</p>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
+348
-306
@@ -3282,349 +3282,316 @@ about these concepts further throughout the rest of the book. Let's move on to
|
||||
the next chapter where we'll look at grouping pieces of data together in a
|
||||
<code>struct</code>.</p>
|
||||
<h1>Structs</h1>
|
||||
<p>A <code>struct</code>, short for "structure", gives us the ability to 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. <code>struct</code> and <code>enum</code> (that we will talk about in the next chapter)
|
||||
are the building blocks you can use in Rust to create new types in your
|
||||
<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>Let’s write a program which calculates the distance between two points.
|
||||
We’ll start off with single variable bindings, and then refactor it to
|
||||
use <code>struct</code>s instead.</p>
|
||||
<p>Let’s make a new project with Cargo called <code>points</code>. Here’s a short program
|
||||
which calculates the distance between two points to put into this project's
|
||||
<code>src/main.rs</code>:</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
|
||||
binding 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("someone@example.com"),
|
||||
username: String::from("someusername123"),
|
||||
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 variable
|
||||
bindings, 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 x1 = 0.0;
|
||||
let y1 = 5.0;
|
||||
let length1 = 50;
|
||||
let width1 = 30;
|
||||
|
||||
let x2 = 12.0;
|
||||
let y2 = 0.0;
|
||||
|
||||
let answer = distance(x1, y1, x2, y2);
|
||||
|
||||
println!("Point 1: ({}, {})", x1, y1);
|
||||
println!("Point 2: ({}, {})", x2, y2);
|
||||
println!("Distance: {}", answer);
|
||||
println!(
|
||||
"The area of the rectangle is {} square pixels.",
|
||||
area(length1, width1)
|
||||
);
|
||||
}
|
||||
|
||||
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
|
||||
let x_squared = f64::powi(x2 - x1, 2);
|
||||
let y_squared = f64::powi(y2 - y1, 2);
|
||||
|
||||
f64::sqrt(x_squared + y_squared)
|
||||
fn area(length: u32, width: u32) -> u32 {
|
||||
length * width
|
||||
}
|
||||
</code></pre>
|
||||
<p>Let's try running this program with <code>cargo run</code>:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling points v0.1.0 (file:///projects/points)
|
||||
Running `target/debug/points`
|
||||
Point 1: (0, 5)
|
||||
Point 2: (12, 0)
|
||||
Distance: 13
|
||||
<pre><code class="language-bash">The area of the rectangle is 1500 square pixels.
|
||||
</code></pre>
|
||||
<p>Let's take a quick look at <code>distance()</code> before we move forward. To find the
|
||||
distance between two points, we can use the Pythagorean Theorem. The theorem is
|
||||
named after Pythagoras, who was the first person to mathematically prove this
|
||||
formula. The details aren't that important; just know the theorem says that the
|
||||
formula for the distance between two points is equal to:</p>
|
||||
<ul>
|
||||
<li>squaring the distance between the points horizontally (the "x" direction)</li>
|
||||
<li>squaring the distance between the points vertically (the "y" direction)</li>
|
||||
<li>adding those together</li>
|
||||
<li>and taking the square root of that.</li>
|
||||
</ul>
|
||||
<p>So that's what we're implementing here.</p>
|
||||
<pre><code class="language-rust,ignore">f64::powi(2.0, 3)
|
||||
<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) -> u32 {
|
||||
</code></pre>
|
||||
<p>The double colon (<code>::</code>) here is a namespace operator. We haven’t talked about
|
||||
modules and namespaces in depth yet, but you can think of the <code>powi()</code> function
|
||||
as being scoped inside of another name. In this case, the name is <code>f64</code>, the
|
||||
same as the type. The <code>powi()</code> function takes two arguments: the first is a
|
||||
number, and the second is the power that it raises that number to. In this
|
||||
case, the second number is an integer, hence the <code>i</code> in its name. Similarly,
|
||||
<code>sqrt()</code> is a function under the <code>f64</code> module, which takes the square root of
|
||||
its argument.</p>
|
||||
<h2>Why <code>struct</code>s?</h2>
|
||||
<p>Our little program is okay, but we can do better. The key to seeing this is in
|
||||
the signature of <code>distance()</code>:</p>
|
||||
<pre><code class="language-rust,ignore">fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
|
||||
</code></pre>
|
||||
<p>The distance function is supposed to calculate the distance between two points.
|
||||
But our distance function calculates some distance between four numbers. The
|
||||
first two and last two arguments are related, but that’s not expressed anywhere
|
||||
in our program itself. It would be nicer if we had a way to group <code>(x1, y1)</code>
|
||||
and <code>(x2, y2)</code> together.</p>
|
||||
<p>We’ve already discussed one way to do that: tuples. Here’s a version of our
|
||||
program which uses tuples:</p>
|
||||
<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 p1 = (0.0, 5.0);
|
||||
let rect1 = (50, 30);
|
||||
|
||||
let p2 = (12.0, 0.0);
|
||||
|
||||
let answer = distance(p1, p2);
|
||||
|
||||
println!("Point 1: {:?}", p1);
|
||||
println!("Point 2: {:?}", p2);
|
||||
println!("Distance: {}", answer);
|
||||
println!(
|
||||
"The area of the rectangle is {} square pixels.",
|
||||
area(rect1)
|
||||
);
|
||||
}
|
||||
|
||||
fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 {
|
||||
let x_squared = f64::powi(p2.0 - p1.0, 2);
|
||||
let y_squared = f64::powi(p2.1 - p1.1, 2);
|
||||
|
||||
f64::sqrt(x_squared + y_squared)
|
||||
fn area(dimensions: (u32, u32)) -> u32 {
|
||||
dimensions.0 * dimensions.1
|
||||
}
|
||||
</code></pre>
|
||||
<p>This is a little better, for sure. Tuples let us add a little bit of structure.
|
||||
We’re now passing two arguments, so that’s more clear. But it’s also worse:
|
||||
<!-- 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:</p>
|
||||
<pre><code class="language-rust,ignore">p2.0 - p1.0
|
||||
p2.1 - p1.1
|
||||
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>When writing this example, your authors almost got it wrong themselves! Distance
|
||||
is all about <code>x</code> and <code>y</code> points, but our code is talking about <code>0</code> and <code>1</code>.
|
||||
This isn’t great.</p>
|
||||
<p>Enter <code>struct</code>s. We can transform our tuples into something with a name for the
|
||||
whole as well as names for the parts:</p>
|
||||
<pre><code class="language-rust,ignore">let p1 = (0.0, 5.0);
|
||||
|
||||
struct Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
}
|
||||
|
||||
let p1 = Point { x: 0.0, y: 5.0 };
|
||||
</code></pre>
|
||||
<p>Here we've defined a <code>struct</code> and given it the name <code>Point</code>. The parts inside
|
||||
<code>{}</code> are defining the <em>fields</em> of the struct. We can have as many or as few of
|
||||
them as we'd like, and we give them a name and specify their type. Here we have
|
||||
two fields named <code>x</code> and <code>y</code>, and they both hold <code>f64</code>s.</p>
|
||||
<p>We can access the field of a struct in the same way we access an element of
|
||||
a tuple, except we use its name:</p>
|
||||
<pre><code class="language-rust,ignore">let p1 = (0.0, 5.0);
|
||||
let x = p1.0;
|
||||
|
||||
struct Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
}
|
||||
|
||||
let p1 = Point { x: 0.0, y: 5.0 };
|
||||
let x = p1.x;
|
||||
</code></pre>
|
||||
<p>Let’s convert our program to use our <code>Point</code> <code>struct</code>. Here’s what it looks
|
||||
like now:</p>
|
||||
<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">#[derive(Debug,Copy,Clone)]
|
||||
struct Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
<pre><code class="language-rust">struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let p1 = Point { x: 0.0, y: 5.0};
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
|
||||
let p2 = Point { x: 12.0, y: 0.0};
|
||||
|
||||
let answer = distance(p1, p2);
|
||||
|
||||
println!("Point 1: {:?}", p1);
|
||||
println!("Point 2: {:?}", p2);
|
||||
println!("Distance: {}", answer);
|
||||
println!(
|
||||
"The area of the rectangle is {} square pixels.",
|
||||
area(&rect1)
|
||||
);
|
||||
}
|
||||
|
||||
fn distance(p1: Point, p2: Point) -> f64 {
|
||||
let x_squared = f64::powi(p2.x - p1.x, 2);
|
||||
let y_squared = f64::powi(p2.y - p1.y, 2);
|
||||
|
||||
f64::sqrt(x_squared + y_squared)
|
||||
fn area(rectangle: &Rectangle) -> u32 {
|
||||
rectangle.length * rectangle.width
|
||||
}
|
||||
</code></pre>
|
||||
<p>Our function signature for <code>distance()</code> now says exactly what we mean: it
|
||||
calculates the distance between two <code>Point</code>s. And rather than <code>0</code> and <code>1</code>,
|
||||
we’ve got back our <code>x</code> and <code>y</code>. This is a win for clarity.</p>
|
||||
<h2>Derived Traits</h2>
|
||||
<p>There’s one other thing that’s a bit strange here, this stuff above the
|
||||
<code>struct</code> declaration:</p>
|
||||
<pre><code class="language-rust,ignore">#[derive(Debug,Copy,Clone)]
|
||||
struct Point {
|
||||
</code></pre>
|
||||
<p>This is an annotation that tells the compiler our struct should get some
|
||||
default behavior for the <code>Debug</code>, <code>Copy</code>, and <code>Clone</code> traits. We talked about
|
||||
marking that types can be <code>Copy</code> and <code>Clone</code>-able in Chapter XX when we
|
||||
discussed ownership. <code>Debug</code> is the trait that enables us to print out our
|
||||
struct so that we can see its value while we are debugging our code.</p>
|
||||
<p>So far, we’ve been printing values using <code>{}</code> in a <code>println!</code> macro. If we try
|
||||
that with a struct, however, by default, we'll get an error. Say we have the
|
||||
following program:</p>
|
||||
<!-- 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>&</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 Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
<pre><code class="language-rust,ignore">struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let p1 = Point { x: 0.0, y: 5.0};
|
||||
println!("Point 1: {}", p1);
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
|
||||
println!("rect1 is {}", rect1);
|
||||
}
|
||||
</code></pre>
|
||||
<p>This code tries to print the <code>p1</code> point directly, which may seem innocuous. But
|
||||
running it produces the following output:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling points v0.1.0 (file:///projects/points)
|
||||
error: the trait bound `Point: std::fmt::Display` is not satisfied [--explain E0277]
|
||||
--> src/main.rs:8:29
|
||||
8 |> println!("Point 1: {}", p1);
|
||||
|> ^^
|
||||
<std macros>:2:27: 2:58: note: in this expansion of format_args!
|
||||
<std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>)
|
||||
src/main.rs:8:5: 8:33: note: in this expansion of println! (defined in <std macros>)
|
||||
note: `Point` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
|
||||
note: required by `std::fmt::Display::fmt`
|
||||
<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>Whew! The core of the error is this part: <em>the trait bound <code>Point: std::fmt::Display</code> is not satisfied</em>. <code>println!</code> can do many kinds of
|
||||
formatting. By default, <code>{}</code> implements a kind of formatting known as
|
||||
<code>Display</code>: output intended for direct end-user consumption. The primitive types
|
||||
we’ve seen implement <code>Display</code>, as there’s only one way you’d show a <code>1</code> to a
|
||||
user. But with structs, the output is less clear. Do you want commas or not?
|
||||
What about the <code>{}</code>s? Should all the fields be shown?</p>
|
||||
<p>More complex types in the standard library and that are defined by the
|
||||
programmer do not automatically implement <code>Display</code> formatting. Standard
|
||||
library types implement <code>Debug</code> formatting, which is intended for the
|
||||
programmer to see. The <code>#[derive(Debug)]</code> annotation lets us use a default
|
||||
implementation of <code>Debug</code> formatting to easily get this ability for types we've
|
||||
defined. To ask <code>println!</code> to use <code>Debug</code> formatting with our <code>Point</code>, we add
|
||||
the annotation to derive the trait and include <code>:?</code> in the print string, like
|
||||
this:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<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!("rect1 is {:?}", 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 compliler 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 Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let p1 = Point { x: 0.0, y: 5.0};
|
||||
println!("Point 1: {:?}", p1);
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
|
||||
println!("rect1 is {:?}", rect1);
|
||||
}
|
||||
</code></pre>
|
||||
<p>If you run this, it should print the values of each field in the <code>Point</code> struct
|
||||
as desired:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling points v0.1.0 (file:///projects/points)
|
||||
Running `target/debug/points`
|
||||
Point 1: Point { x: 0, y: 5 }
|
||||
<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>You’ll see this repeated later with other types. We’ll cover traits fully in
|
||||
Chapter XX.</p>
|
||||
<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>
|
||||
<h2>Method Syntax</h2>
|
||||
<p>In Chapter 4 when we discussed ownership, we made several references to
|
||||
<em>methods</em>. Methods look like this:</p>
|
||||
<pre><code class="language-rust">let s1 = "hello";
|
||||
|
||||
// call a method on s1
|
||||
let s2 = s1.clone();
|
||||
|
||||
println!("{}", s1);
|
||||
</code></pre>
|
||||
<p>The call to <code>clone()</code> is attached to <code>s1</code> with a dot. This is called <em>method
|
||||
syntax</em>, and it’s a way to call certain functions with a different style.</p>
|
||||
<p>Why have two ways to call functions? We’ll talk about some deeper reasons
|
||||
related to ownership in a moment, but one big reason is that methods look nicer
|
||||
when chained together:</p>
|
||||
<pre><code class="language-rust,ignore">// with functions
|
||||
h(g(f(x)));
|
||||
|
||||
// with methods
|
||||
x.f().g().h();
|
||||
</code></pre>
|
||||
<p>The nested-functions version reads in reverse: the program executes <code>f()</code>, then
|
||||
<code>g()</code>, then <code>h()</code>, but we read it left-to-right as <code>h()</code>, then <code>g()</code>, then
|
||||
<code>f()</code>. The method syntax is executed in the same order as we would read it.</p>
|
||||
<p>Before we get into the details, let’s talk about how to define your own
|
||||
methods.</p>
|
||||
<h3>Defining methods</h3>
|
||||
<p>We can define methods with the <code>impl</code> keyword. <code>impl</code> is short for
|
||||
<em>implementation</em>. Doing so looks like this:</p>
|
||||
<pre><code class="language-rust">#[derive(Debug,Copy,Clone)]
|
||||
struct Point {
|
||||
x: f64,
|
||||
y: f64,
|
||||
<p><em>Methods</em> are similar to functions: they're declared with the <code>fn</code> keyword and
|
||||
their name, they can take arguments and return values, and they contain some
|
||||
code that gets run when they're called from somewhere else. Methods are
|
||||
different from functions, however, because they're defined within the context
|
||||
of a struct (or an enum or a trait object, which we will cover in Chapters 6
|
||||
and XX respectively), and their first argument is always <code>self</code>, which
|
||||
represents the instance of the struct that the method is being called on.</p>
|
||||
<h3>Defining Methods</h3>
|
||||
<p>Let's change our <code>area</code> function that takes a <code>Rectangle</code> instance as an
|
||||
argument and instead make an <code>area</code> method defined on the <code>Rectangle</code> struct:</p>
|
||||
<pre><code class="language-rust">#[derive(Debug)]
|
||||
struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
}
|
||||
|
||||
impl Point {
|
||||
fn distance(&self, other: &Point) -> f64 {
|
||||
let x_squared = f64::powi(other.x - self.x, 2);
|
||||
let y_squared = f64::powi(other.y - self.y, 2);
|
||||
|
||||
f64::sqrt(x_squared + y_squared)
|
||||
impl Rectangle {
|
||||
fn area(&self) -> u32 {
|
||||
self.length * self.width
|
||||
}
|
||||
}
|
||||
|
||||
let p1 = Point { x: 0.0, y: 0.0 };
|
||||
let p2 = Point { x: 5.0, y: 6.5 };
|
||||
fn main() {
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
|
||||
assert_eq!(8.200609733428363, p1.distance(&p2));
|
||||
</code></pre>
|
||||
<p>Let’s break this down. First, we have our <code>Point</code> struct from earlier in the
|
||||
chapter. Next comes our first use of the <code>impl</code> keyword:</p>
|
||||
<pre><code class="language-rust,ignore">impl Point {
|
||||
// ...
|
||||
println!(
|
||||
"The area of the rectangle is {} square pixels.",
|
||||
rect1.area()
|
||||
);
|
||||
}
|
||||
</code></pre>
|
||||
<p>Everything we put inside of the curly braces will be methods implemented on
|
||||
<code>Point</code>. Next is our definition:</p>
|
||||
<pre><code class="language-rust,ignore">fn distance(&self, other: &Point) -> f64 {
|
||||
// ...
|
||||
}
|
||||
</code></pre>
|
||||
<p>Other than this, the rest of the example is familiar: an implementation of
|
||||
<code>distance()</code> and using the method to find an answer.</p>
|
||||
<p>Our definition of <code>distance()</code> here as a method looks very similar to our
|
||||
previous definition of <code>distance()</code> as a function, but with two differences.
|
||||
Here's the <code>distance()</code> function again:</p>
|
||||
<pre><code class="language-rust,ignore">fn distance(p1: Point, p2: Point) -> f64 {
|
||||
// ...
|
||||
}
|
||||
</code></pre>
|
||||
<p>The first difference is in the first argument. Instead of a name and a type, we
|
||||
have written <code>&self</code>. This is what distinguishes a method from a function:
|
||||
using <code>self</code> inside of an <code>impl</code> block means we have a method. Because we
|
||||
already know that we are implementing this method on <code>Point</code> because of the
|
||||
surrounding <code>impl Point</code> block, we don’t need to write the type of <code>self</code> out.</p>
|
||||
<p>Note that we have written <code>&self</code>, not just <code>self</code>. This is because we want to
|
||||
take a reference to our argument's value rather than taking ownership of it. In
|
||||
other words, these two forms are the same:</p>
|
||||
<pre><code class="language-rust,ignore">fn foo(self: &Point)
|
||||
fn foo(&self)
|
||||
</code></pre>
|
||||
<p>Just like any other parameter, you can take <code>self</code> in three forms. Here’s the
|
||||
list, with the most common form first:</p>
|
||||
<pre><code class="language-rust,ignore">fn foo(&self) // take self by reference
|
||||
fn foo(&mut self) // take self by mutable reference
|
||||
fn foo(self) // take self by ownership
|
||||
</code></pre>
|
||||
<p>In this case, we only need a reference. We don’t need to mutate either <code>Point</code>
|
||||
to get the distance between them, so we won't take a mutable reference to the
|
||||
<code>Point</code> that we call the method on. Methods that take ownership of <code>self</code> are
|
||||
rarely used. An example of a time to do that would be if we wanted to have a
|
||||
method that would transform <code>self</code> into something else and prevent other code
|
||||
from using the value of <code>self</code> after the transformation happens.</p>
|
||||
<h4>Methods and automatic referencing</h4>
|
||||
<p>We’ve left out an important detail. It’s in this line of the example:</p>
|
||||
<pre><code class="language-rust,ignore">assert_eq!(8.200609733428363, p1.distance(&p2));
|
||||
</code></pre>
|
||||
<p>When we defined <code>distance()</code>, we took both <code>self</code> and the other argument by
|
||||
reference. Yet, we needed a <code>&</code> for <code>p2</code> but not <code>p1</code>. What gives?</p>
|
||||
<p>This feature is called <em>automatic referencing</em>, and calling methods is one
|
||||
of the few places in Rust that has behavior like this. Here’s how it works:
|
||||
when you call a method with <code>self.(</code>, Rust will automatically add in <code>&</code>s
|
||||
or <code>&mut</code>s to match the signature. In other words, these are the same:</p>
|
||||
<!-- Will add ghosting and wingdings here in libreoffice /Carol -->
|
||||
<p>In order to make the function be defined within the context of <code>Rectangle</code>, we
|
||||
start an <code>impl</code> block (<code>impl</code> is short for <em>implementation</em>). Then we move the
|
||||
function within the <code>impl</code> curly braces, and change the first (and in this
|
||||
case, only) argument to be <code>self</code> in the signature and everywhere within the
|
||||
body. Then in <code>main</code> where we called the <code>area</code> function and passed <code>rect1</code> as
|
||||
an argument, we can instead use <em>method syntax</em> to call the <code>area</code> method on
|
||||
our <code>Rectangle</code> instance.</p>
|
||||
<p>In the signature for <code>area</code>, we get to use <code>&self</code> instead of <code>rectangle: &Rectangle</code> because Rust knows the type of <code>self</code> is <code>Rectangle</code> due to this
|
||||
method being inside the <code>impl Rectangle</code> context. Note we still need to have
|
||||
the <code>&</code> before <code>self</code>, just like we had <code>&Rectangle</code>. Methods can choose to
|
||||
take ownership of <code>self</code>, borrow <code>self</code> immutably as we've done here, or borrow
|
||||
<code>self</code> mutably, just like any other argument.</p>
|
||||
<p>We've chosen <code>&self</code> here for the same reason we used <code>&Rectangle</code> in the
|
||||
function version: we don't want to take ownership, and we just want to be able
|
||||
to read the data in the struct, not write to it. If we wanted to be able to
|
||||
change the instance that we've called the method on as part of what the method
|
||||
does, we'd put <code>&mut self</code> as the first argument instead. Having a method that
|
||||
takes ownership of the instance by having just <code>self</code> as the first argument is
|
||||
rarer; this is usually used when the method transforms <code>self</code> into something
|
||||
else and we want to prevent the caller from using the original instance after
|
||||
the transformation.</p>
|
||||
<p>The main benefit of using methods over functions, in addition to getting to use
|
||||
method syntax and not having to repeat the type of <code>self</code> in every method's
|
||||
signature, is for organization. We've put all the things we can do with an
|
||||
instance of a type together in one <code>impl</code> block, rather than make future users
|
||||
of our code search for capabilities of <code>Rectangle</code> all over the place.</p>
|
||||
<!-- PROD: START BOX -->
|
||||
<h4>Where's the <code>-></code> operator?</h4>
|
||||
<p>In languages like C++, there are two different operators for calling methods:
|
||||
<code>.</code> if you're calling a method on the object directly, and <code>-></code> if you're
|
||||
calling the method on a pointer to the object and thus need to dereference the
|
||||
pointer first. In other words, if <code>object</code> is a pointer, <code>object->something()</code>
|
||||
is like <code>(*object).something()</code>.</p>
|
||||
<p>Rust doesn't have an equivalent to the <code>-></code> operator; instead, Rust has a
|
||||
feature called <em>automatic referencing and dereferencing</em>. Calling methods is
|
||||
one of the few places in Rust that has behavior like this.</p>
|
||||
<p>Here’s how it works: when you call a method with <code>object.something()</code>, Rust
|
||||
will automatically add in <code>&</code>, <code>&mut</code>, or <code>*</code> so that <code>object</code> matches the
|
||||
signature of the method. In other words, these are the same:</p>
|
||||
<pre><code class="language-rust"># #[derive(Debug,Copy,Clone)]
|
||||
# struct Point {
|
||||
# x: f64,
|
||||
@@ -3644,25 +3611,100 @@ or <code>&mut</code>s to match the signature. In other words, these are the
|
||||
p1.distance(&p2);
|
||||
(&p1).distance(&p2);
|
||||
</code></pre>
|
||||
<p>The first one looks much, much cleaner. Here’s another example:</p>
|
||||
<pre><code class="language-rust">let mut s = String::from("Hello,");
|
||||
<p>The first one looks much, much cleaner. This automatic referencing behavior
|
||||
works because methods have a clear receiver — the type of <code>self</code>. Given the
|
||||
receiver and name of a method, Rust can figure out definitively whether the
|
||||
method is just reading (so needs <code>&self</code>), mutating (so <code>&mut self</code>), or
|
||||
consuming (so <code>self</code>). The fact that Rust makes borrowing implicit for method
|
||||
receivers is a big part of making ownership ergonomic in practice.</p>
|
||||
<!-- PROD: END BOX -->
|
||||
<h3>Methods with More Arguments</h3>
|
||||
<p>Let's practice some more with methods by implementing a second method on our
|
||||
<code>Rectangle</code> struct. This time, we'd like for an instance of <code>Rectangle</code> to take
|
||||
another instance of <code>Rectangle</code> and return <code>true</code> if the second rectangle could
|
||||
fit completely within <code>self</code> and <code>false</code> if it would not. That is, if we run
|
||||
this code:</p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let rect1 = Rectangle { length: 50, width: 30 };
|
||||
let rect2 = Rectangle { length: 40, width: 10 };
|
||||
let rect3 = Rectangle { length: 45, width: 60 };
|
||||
|
||||
s.push_str(" world!");
|
||||
|
||||
// The above is the same as:
|
||||
// (&mut s).push_str(" world!");
|
||||
|
||||
assert_eq!("Hello, world!", s);
|
||||
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
|
||||
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
|
||||
}
|
||||
</code></pre>
|
||||
<p>Because [<code>push_str()</code>][pushstr]<!-- ignore --> has the following signature:</p>
|
||||
<pre><code class="language-rust,ignore">fn push_str(&mut self, string: &str) {
|
||||
<p>We want to see this output, since both of <code>rect2</code>'s dimensions are smaller than
|
||||
<code>rect1</code>'s, but <code>rect3</code> is wider than <code>rect1</code>:</p>
|
||||
<pre><code class="language-bash">Can rect1 hold rect2? true
|
||||
Can rect1 hold rect3? false
|
||||
</code></pre>
|
||||
<p>This automatic referencing behavior works because methods have a clear receiver
|
||||
— the type of <code>self</code> — and in most cases it’s clear given the receiver and name
|
||||
of a method whether the method is just reading (so needs <code>&self</code>), mutating (so
|
||||
<code>&mut self</code>), or consuming (so <code>self</code>). The fact that Rust makes borrowing
|
||||
implicit for method receivers is a big part of making ownership ergonomic in
|
||||
practice.</p>
|
||||
<p>We know we want to define a method, so it will be within the <code>impl Rectangle</code>
|
||||
block. The method name will be <code>can_hold</code>, and it will take an immutable borrow
|
||||
of another <code>Rectangle</code> as an argument. We can tell what the type of the
|
||||
argument will be by looking at a call site: <code>rect1.can_hold(&rect2)</code> passes in
|
||||
<code>&rect2</code>, which is an immutable borrow to <code>rect2</code>, an instance of <code>Rectangle</code>.
|
||||
This makes sense, since we only need to read <code>rect2</code> (rather than write, which
|
||||
would mean we'd need a mutable borrow) and we want <code>main</code> to keep ownership of
|
||||
<code>rect2</code> so that we could use it again after calling this method. The return
|
||||
value of <code>can_hold</code> will be a boolean, and the implementation will check to see
|
||||
if <code>self</code>'s length and width are both greater than the length and width of the
|
||||
other <code>Rectagle</code>, respectively. Let's write that code!</p>
|
||||
<pre><code># #[derive(Debug)]
|
||||
# struct Rectangle {
|
||||
# length: u32,
|
||||
# width: u32,
|
||||
# }
|
||||
#
|
||||
impl Rectangle {
|
||||
fn area(&self) -> u32 {
|
||||
self.length * self.width
|
||||
}
|
||||
|
||||
fn can_hold(&self, other: &Rectangle) -> bool {
|
||||
self.length > other.length && self.width > other.width
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<!-- Will add ghosting here in libreoffice /Carol -->
|
||||
<p>If we run this with the <code>main</code> from earlier, we will get our desired output!
|
||||
Methods can take multiple arguments that we add to the signature after the
|
||||
<code>self</code> parameter, and those arguments work just like arguments in functions do.</p>
|
||||
<h3>Associated Functions</h3>
|
||||
<p>One more useful feature of <code>impl</code> blocks: we're allowed to define functions
|
||||
within <code>impl</code> blocks that <em>don't</em> take <code>self</code> as a parameter. These are called
|
||||
<em>associated functions</em>, since they're associated with the struct. They're still
|
||||
functions though, not methods, since they don't have an instance of the struct
|
||||
to work with. You've already used an associated function: <code>String::from</code>.</p>
|
||||
<p>Associated functions are often used for constructors that will return a new
|
||||
instance of the struct. For example, we could provide an associated function
|
||||
that would take one dimension argument and use that as both length and width,
|
||||
thus making it easier to create a square <code>Rectangle</code> rather than having to
|
||||
specify the same value twice:</p>
|
||||
<pre><code class="language-rust"># #[derive(Debug)]
|
||||
# struct Rectangle {
|
||||
# length: u32,
|
||||
# width: u32,
|
||||
# }
|
||||
#
|
||||
impl Rectangle {
|
||||
fn square(size: u32) -> Rectangle {
|
||||
Rectangle { length: size, width: size }
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<p>To call this associated function, we use the <code>::</code> syntax with the struct name:
|
||||
<code>let sq = Rectange::square(3);</code>, for example. It's kind of this function is
|
||||
namespaced by the struct: the <code>::</code> syntax is used for both associated functions
|
||||
and namespaces created by modules, which we'll learn about in Chapter 7.</p>
|
||||
<h2>Summary</h2>
|
||||
<p>Structs let us create custom types that are meaningful for our domain. By using
|
||||
structs, we can keep associated pieces of data connected to each other and name
|
||||
each piece to make our code clear. Methods let us specify the behavior that
|
||||
instances of our structs have, and associated functions let us namespace
|
||||
functionality that is particular to our struct without having an instance
|
||||
available.</p>
|
||||
<p>Structs aren't the only way we can create custom types, though; let's turn to
|
||||
the <code>enum</code> feature of Rust and add another tool to our toolbox.</p>
|
||||
<h1>Enums</h1>
|
||||
<p>Next, let’s look at <em>enumerations</em>, which allow you to define a type by
|
||||
enumerating its possible values. Commonly called "enums", these unlock a lot of
|
||||
|
||||
Reference in New Issue
Block a user