Files
docs-rust/ch05/ch05-03-method-syntax.html
2026-06-22 21:27:36 +05:30

352 lines
19 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>Methods</title>
</head>
<body>
<h2 id="methods"><a class="header" href="#methods">Methods</a></h2>
<p>Methods are similar to functions: We declare them with the <code>fn</code> keyword and a
name, they can have parameters and a return value, and they contain some code
thats run when the method is called from somewhere else. Unlike functions,
methods are defined within the context of a struct (or an enum or a trait
object, which we cover in <a href="../ch06/ch06-00-enums.html">Chapter 6</a><!-- ignore --> and <a href="../ch18/ch18-02-trait-objects.html">Chapter
18</a><!-- ignore -->, respectively), and their first parameter is
always <code>self</code>, which represents the instance of the struct the method is being
called on.</p>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="defining-methods"></a></p>
<h3 id="method-syntax"><a class="header" href="#method-syntax">Method Syntax</a></h3>
<p>Lets change the <code>area</code> function that has a <code>Rectangle</code> instance as a parameter
and instead make an <code>area</code> method defined on the <code>Rectangle</code> struct, as shown
in Listing 5-13.</p>
<figure class="listing" id="listing-5-13">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024">#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
}</code></pre>
<figcaption><a href="#listing-5-13">Listing 5-13</a>: Defining an <code>area</code> method on the <code>Rectangle</code> struct</figcaption>
</figure>
<p>To define the function within the context of <code>Rectangle</code>, we start an <code>impl</code>
(implementation) block for <code>Rectangle</code>. Everything within this <code>impl</code> block
will be associated with the <code>Rectangle</code> type. Then, we move the <code>area</code> function
within the <code>impl</code> curly brackets and change the first (and in this case, only)
parameter to be <code>self</code> in the signature and everywhere within the body. 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. The method syntax goes after an instance: We add a dot followed by
the method name, parentheses, and any arguments.</p>
<p>In the signature for <code>area</code>, we use <code>&amp;self</code> instead of <code>rectangle: &amp;Rectangle</code>.
The <code>&amp;self</code> is actually short for <code>self: &amp;Self</code>. Within an <code>impl</code> block, the
type <code>Self</code> is an alias for the type that the <code>impl</code> block is for. Methods must
have a parameter named <code>self</code> of type <code>Self</code> for their first parameter, so Rust
lets you abbreviate this with only the name <code>self</code> in the first parameter spot.
Note that we still need to use the <code>&amp;</code> in front of the <code>self</code> shorthand to
indicate that this method borrows the <code>Self</code> instance, just as we did in
<code>rectangle: &amp;Rectangle</code>. Methods can take ownership of <code>self</code>, borrow <code>self</code>
immutably, as weve done here, or borrow <code>self</code> mutably, just as they can any
other parameter.</p>
<p>We chose <code>&amp;self</code> here for the same reason we used <code>&amp;Rectangle</code> in the function
version: We dont want to take ownership, and we just want to read the data in
the struct, not write to it. If we wanted to change the instance that weve
called the method on as part of what the method does, wed use <code>&amp;mut self</code> as
the first parameter. Having a method that takes ownership of the instance by
using just <code>self</code> as the first parameter is rare; this technique is usually
used when the method transforms <code>self</code> into something else and you want to
prevent the caller from using the original instance after the transformation.</p>
<p>The main reason for using methods instead of functions, in addition to
providing method syntax and not having to repeat the type of <code>self</code> in every
methods signature, is for organization. Weve put all the things we can do
with an instance of a type in one <code>impl</code> block rather than making future users
of our code search for capabilities of <code>Rectangle</code> in various places in the
library we provide.</p>
<p>Note that we can choose to give a method the same name as one of the structs
fields. For example, we can define a method on <code>Rectangle</code> that is also named
<code>width</code>:</p>
<figure class="listing">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span>impl Rectangle {
fn width(&amp;self) -&gt; bool {
self.width &gt; 0
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
if rect1.width() {
println!("The rectangle has a nonzero width; it is {}", rect1.width);
}
}</code></pre>
</figure>
<p>Here, were choosing to make the <code>width</code> method return <code>true</code> if the value in
the instances <code>width</code> field is greater than <code>0</code> and <code>false</code> if the value is
<code>0</code>: We can use a field within a method of the same name for any purpose. In
<code>main</code>, when we follow <code>rect1.width</code> with parentheses, Rust knows we mean the
method <code>width</code>. When we dont use parentheses, Rust knows we mean the field
<code>width</code>.</p>
<p>Often, but not always, when we give a method the same name as a field we want
it to only return the value in the field and do nothing else. Methods like this
are called <em>getters</em>, and Rust does not implement them automatically for struct
fields as some other languages do. Getters are useful because you can make the
field private but the method public and thus enable read-only access to that
field as part of the types public API. We will discuss what public and private
are and how to designate a field or method as public or private in <a href="../ch07/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#exposing-paths-with-the-pub-keyword">Chapter
7</a><!-- ignore -->.</p>
<section class="note" aria-role="note">
<h3 id="wheres-the---operator"><a class="header" href="#wheres-the---operator">Wheres the <code>-&gt;</code> Operator?</a></h3>
<p>In C and C++, two different operators are used for calling methods: You use
<code>.</code> if youre calling a method on the object directly and <code>-&gt;</code> if youre
calling the method on a pointer to the object and need to dereference the
pointer first. In other words, if <code>object</code> is a pointer,
<code>object-&gt;something()</code> is similar to <code>(*object).something()</code>.</p>
<p>Rust doesnt have an equivalent to the <code>-&gt;</code> operator; instead, Rust has a
feature called <em>automatic referencing and dereferencing</em>. Calling methods is
one of the few places in Rust with this behavior.</p>
<p>Heres how it works: When you call a method with <code>object.something()</code>, Rust
automatically adds in <code>&amp;</code>, <code>&amp;mut</code>, or <code>*</code> so that <code>object</code> matches the
signature of the method. In other words, the following are the same:</p>
<!-- CAN'T EXTRACT SEE BUG https://github.com/rust-lang/mdBook/issues/1127 -->
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span><span class="boring">#[derive(Debug,Copy,Clone)]
</span><span class="boring">struct Point {
</span><span class="boring"> x: f64,
</span><span class="boring"> y: f64,
</span><span class="boring">}
</span><span class="boring">
</span><span class="boring">impl Point {
</span><span class="boring"> fn distance(&amp;self, other: &amp;Point) -&gt; f64 {
</span><span class="boring"> let x_squared = f64::powi(other.x - self.x, 2);
</span><span class="boring"> let y_squared = f64::powi(other.y - self.y, 2);
</span><span class="boring">
</span><span class="boring"> f64::sqrt(x_squared + y_squared)
</span><span class="boring"> }
</span><span class="boring">}
</span><span class="boring">let p1 = Point { x: 0.0, y: 0.0 };
</span><span class="boring">let p2 = Point { x: 5.0, y: 6.5 };
</span>p1.distance(&amp;p2);
(&amp;p1).distance(&amp;p2);
<span class="boring">}</span></code></pre>
<p>The first one looks 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
reading (<code>&amp;self</code>), mutating (<code>&amp;mut self</code>), or consuming (<code>self</code>). The fact
that Rust makes borrowing implicit for method receivers is a big part of
making ownership ergonomic in practice.</p>
</section>
<h3 id="methods-with-more-parameters"><a class="header" href="#methods-with-more-parameters">Methods with More Parameters</a></h3>
<p>Lets practice using methods by implementing a second method on the <code>Rectangle</code>
struct. This time we want an instance of <code>Rectangle</code> to take another instance
of <code>Rectangle</code> and return <code>true</code> if the second <code>Rectangle</code> can fit completely
within <code>self</code> (the first <code>Rectangle</code>); otherwise, it should return <code>false</code>.
That is, once weve defined the <code>can_hold</code> method, we want to be able to write
the program shown in Listing 5-14.</p>
<figure class="listing" id="listing-5-14">
<span class="file-name">Filename: src/main.rs</span>
<pre><code class="language-rust ignore">fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&amp;rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&amp;rect3));
}</code></pre>
<figcaption><a href="#listing-5-14">Listing 5-14</a>: Using the as-yet-unwritten <code>can_hold</code> method</figcaption>
</figure>
<p>The expected output would look like the following because both dimensions of
<code>rect2</code> are smaller than the dimensions of <code>rect1</code>, but <code>rect3</code> is wider than
<code>rect1</code>:</p>
<pre><code class="language-text">Can rect1 hold rect2? true
Can rect1 hold rect3? false
</code></pre>
<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 a parameter. We can tell what the type of the
parameter will be by looking at the code that calls the method:
<code>rect1.can_hold(&amp;rect2)</code> passes in <code>&amp;rect2</code>, which is an immutable borrow to
<code>rect2</code>, an instance of <code>Rectangle</code>. This makes sense because we only need to
read <code>rect2</code> (rather than write, which would mean wed need a mutable borrow),
and we want <code>main</code> to retain ownership of <code>rect2</code> so that we can use it again
after calling the <code>can_hold</code> method. The return value of <code>can_hold</code> will be a
Boolean, and the implementation will check whether the width and height of
<code>self</code> are greater than the width and height of the other <code>Rectangle</code>,
respectively. Lets add the new <code>can_hold</code> method to the <code>impl</code> block from
Listing 5-13, shown in Listing 5-15.</p>
<figure class="listing" id="listing-5-15">
<span class="file-name">Filename: src/main.rs</span>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span>impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.width * self.height
}
fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
self.width &gt; other.width &amp;&amp; self.height &gt; other.height
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let rect1 = Rectangle {
</span><span class="boring"> width: 30,
</span><span class="boring"> height: 50,
</span><span class="boring"> };
</span><span class="boring"> let rect2 = Rectangle {
</span><span class="boring"> width: 10,
</span><span class="boring"> height: 40,
</span><span class="boring"> };
</span><span class="boring"> let rect3 = Rectangle {
</span><span class="boring"> width: 60,
</span><span class="boring"> height: 45,
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> println!("Can rect1 hold rect2? {}", rect1.can_hold(&amp;rect2));
</span><span class="boring"> println!("Can rect1 hold rect3? {}", rect1.can_hold(&amp;rect3));
</span><span class="boring">}</span></code></pre>
<figcaption><a href="#listing-5-15">Listing 5-15</a>: Implementing the <code>can_hold</code> method on <code>Rectangle</code> that takes another <code>Rectangle</code> instance as a parameter</figcaption>
</figure>
<p>When we run this code with the <code>main</code> function in Listing 5-14, well get our
desired output. Methods can take multiple parameters that we add to the
signature after the <code>self</code> parameter, and those parameters work just like
parameters in functions.</p>
<h3 id="associated-functions"><a class="header" href="#associated-functions">Associated Functions</a></h3>
<p>All functions defined within an <code>impl</code> block are called <em>associated functions</em>
because theyre associated with the type named after the <code>impl</code>. We can define
associated functions that dont have <code>self</code> as their first parameter (and thus
are not methods) because they dont need an instance of the type to work with.
Weve already used one function like this: the <code>String::from</code> function thats
defined on the <code>String</code> type.</p>
<p>Associated functions that arent methods are often used for constructors that
will return a new instance of the struct. These are often called <code>new</code>, but
<code>new</code> isnt a special name and isnt built into the language. For example, we
could choose to provide an associated function named <code>square</code> that would have
one dimension parameter and use that as both width and height, thus making it
easier to create a square <code>Rectangle</code> rather than having to specify the same
value twice:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span>impl Rectangle {
fn square(size: u32) -&gt; Self {
Self {
width: size,
height: size,
}
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let sq = Rectangle::square(3);
</span><span class="boring">}</span></code></pre>
<p>The <code>Self</code> keywords in the return type and in the body of the function are
aliases for the type that appears after the <code>impl</code> keyword, which in this case
is <code>Rectangle</code>.</p>
<p>To call this associated function, we use the <code>::</code> syntax with the struct name;
<code>let sq = Rectangle::square(3);</code> is an example. This function is namespaced by
the struct: The <code>::</code> syntax is used for both associated functions and
namespaces created by modules. Well discuss modules in <a href="../ch07/ch07-02-defining-modules-to-control-scope-and-privacy.html">Chapter
7</a><!-- ignore -->.</p>
<h3 id="multiple-impl-blocks"><a class="header" href="#multiple-impl-blocks">Multiple <code>impl</code> Blocks</a></h3>
<p>Each struct is allowed to have multiple <code>impl</code> blocks. For example, Listing
5-15 is equivalent to the code shown in Listing 5-16, which has each method in
its own <code>impl</code> block.</p>
<figure class="listing" id="listing-5-16">
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#[derive(Debug)]
</span><span class="boring">struct Rectangle {
</span><span class="boring"> width: u32,
</span><span class="boring"> height: u32,
</span><span class="boring">}
</span><span class="boring">
</span>impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.width * self.height
}
}
impl Rectangle {
fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
self.width &gt; other.width &amp;&amp; self.height &gt; other.height
}
}
<span class="boring">
</span><span class="boring">fn main() {
</span><span class="boring"> let rect1 = Rectangle {
</span><span class="boring"> width: 30,
</span><span class="boring"> height: 50,
</span><span class="boring"> };
</span><span class="boring"> let rect2 = Rectangle {
</span><span class="boring"> width: 10,
</span><span class="boring"> height: 40,
</span><span class="boring"> };
</span><span class="boring"> let rect3 = Rectangle {
</span><span class="boring"> width: 60,
</span><span class="boring"> height: 45,
</span><span class="boring"> };
</span><span class="boring">
</span><span class="boring"> println!("Can rect1 hold rect2? {}", rect1.can_hold(&amp;rect2));
</span><span class="boring"> println!("Can rect1 hold rect3? {}", rect1.can_hold(&amp;rect3));
</span><span class="boring">}</span></code></pre>
<figcaption><a href="#listing-5-16">Listing 5-16</a>: Rewriting Listing 5-15 using multiple <code>impl</code> blocks</figcaption>
</figure>
<p>Theres no reason to separate these methods into multiple <code>impl</code> blocks here,
but this is valid syntax. Well see a case in which multiple <code>impl</code> blocks are
useful in Chapter 10, where we discuss generic types and traits.</p>
<h2 id="summary"><a class="header" href="#summary">Summary</a></h2>
<p>Structs let you create custom types that are meaningful for your domain. By
using structs, you can keep associated pieces of data connected to each other
and name each piece to make your code clear. In <code>impl</code> blocks, you can define
functions that are associated with your type, and methods are a kind of
associated function that let you specify the behavior that instances of your
structs have.</p>
<p>But structs arent the only way you can create custom types: Lets turn to
Rusts enum feature to add another tool to your toolbox.</p>
</body>
</html>