Files
book/ch05-01-method-syntax.html
T

258 lines
16 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-variable-bindings-and-mutability.html"><strong>3.1.</strong> Variable Bindings 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"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html" class="active"><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> if let</a></li></ul></li><li><strong>7.</strong> Crates &amp; Modules</li><li><strong>8.</strong> Error Handling</li><li><strong>9.</strong> Basic Collections</li><li><ul class="section"><li><strong>9.1.</strong> Vectors</li><li><strong>9.2.</strong> Strings</li><li><strong>9.3.</strong> <code>HashMap&lt;K, V&gt;</code></li></ul></li><li><strong>10.</strong> Lifetimes</li><li><a href="chZZ-generics.html"><strong>11.</strong> Generics</a></li><li><strong>12.</strong> Traits</li><li><strong>13.</strong> Closures</li><li><strong>14.</strong> Iterators</li><li><a href="chXX-patterns.html"><strong>15.</strong> Patterns</a></li><li><strong>16.</strong> I/O</li><li><ul class="section"><li><strong>16.1.</strong> <code>Read</code> &amp; <code>Write</code></li><li><strong>16.2.</strong> <code>std::fs</code></li><li><strong>16.3.</strong> <code>std::path</code></li><li><strong>16.4.</strong> <code>std::env</code></li></ul></li><li><strong>17.</strong> Testing</li><li><strong>18.</strong> Smart Pointers</li><li><ul class="section"><li><strong>18.1.</strong> <code>Deref</code></li><li><strong>18.2.</strong> <code>Deref</code> coercions</li><li><strong>18.3.</strong> <code>Box&lt;T&gt;</code></li><li><strong>18.4.</strong> <code>Rc&lt;T&gt;</code></li></ul></li><li><strong>19.</strong> Concurrency</li><li><ul class="section"><li><strong>19.1.</strong> Threads</li><li><strong>19.2.</strong> <code>Send</code> &amp; <code>Sync</code></li><li><strong>19.3.</strong> <code>Arc&lt;T&gt;</code></li><li><strong>19.4.</strong> <code>Mutex&lt;T&gt;</code></li><li><strong>19.5.</strong> <code>Channels</code></li></ul></li><li><strong>20.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>20.1.</strong> Raw Pointers</li><li><strong>20.2.</strong> transmute</li></ul></li><li><strong>21.</strong> FFI</li><li><ul class="section"><li><strong>21.1.</strong> Conditional Compilation</li><li><strong>21.2.</strong> Bindings to C</li><li><strong>21.3.</strong> Using Rust from Other Languages</li><li><strong>21.4.</strong> <code>static</code></li></ul></li><li><strong>22.</strong> Creating a Library</li><li><ul class="section"><li><strong>22.1.</strong> Cargo</li><li><strong>22.2.</strong> Crates.io</li><li><a href="chYY-YY-documentation.html"><strong>22.3.</strong> Documentation</a></li><li><a href="chYY-YY-workspaces.html"><strong>22.4.</strong> Workspaces and Multiple Related Crates</a></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> Interior mutability</li><li><ul class="section"><li><strong>24.1.</strong> <code>Cell&lt;T&gt;</code></li><li><strong>24.2.</strong> <code>RefCell&lt;T&gt;</code></li></ul></li><li><strong>25.</strong> Macros</li><li><strong>26.</strong> Nightly Rust</li><li><a href="appendix-00.html"><strong>27.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>27.1.</strong> Keywords</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">
<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 = &quot;hello&quot;;
// call a method on s1
let s2 = s1.clone();
println!(&quot;{}&quot;, 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,
}
impl Point {
fn distance(&amp;self, other: &amp;Point) -&gt; 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)
}
}
let p1 = Point { x: 0.0, y: 0.0 };
let p2 = Point { x: 5.0, y: 6.5 };
assert_eq!(8.200609733428363, p1.distance(&amp;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 {
// ...
}
</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(&amp;self, other: &amp;Point) -&gt; 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) -&gt; f64 {
// ...
}
</code></pre>
<p>The first difference is in the first argument. Instead of a name and a type, we
have written <code>&amp;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>&amp;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: &amp;Point)
fn foo(&amp;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(&amp;self) // take self by reference
fn foo(&amp;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(&amp;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>&amp;</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>&amp;</code>s
or <code>&amp;mut</code>s to match the signature. In other words, these are the same:</p>
<pre><code class="language-rust"># #[derive(Debug,Copy,Clone)]
# struct Point {
# x: f64,
# y: f64,
# }
#
# impl Point {
# fn distance(&amp;self, other: &amp;Point) -&gt; 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)
# }
# }
# let p1 = Point { x: 0.0, y: 0.0 };
# let p2 = Point { x: 5.0, y: 6.5 };
p1.distance(&amp;p2);
(&amp;p1).distance(&amp;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(&quot;Hello,&quot;);
s.push_str(&quot; world!&quot;);
// The above is the same as:
// (&amp;mut s).push_str(&quot; world!&quot;);
assert_eq!(&quot;Hello, world!&quot;, s);
</code></pre>
<p>Because <a href="../collections/string/struct.String.html#method.push_str"><code>push_str()</code></a> has the following signature:</p>
<pre><code class="language-rust,ignore">fn push_str(&amp;mut self, string: &amp;str) {
</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>&amp;self</code>), mutating (so
<code>&amp;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>
</div>
<!-- Mobile navigation buttons -->
<a href="ch05-00-structs.html" class="mobile-nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="ch06-00-enums.html" class="mobile-nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<a href="ch05-00-structs.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="ch06-00-enums.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>