<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Impl on Semonan Book</title><link>https://semonan.com/en/tags/impl/</link><description>Recent content in Impl on Semonan Book</description><generator>Hugo</generator><language>en-US</language><lastBuildDate>Thu, 11 Jul 2024 00:00:00 +0000</lastBuildDate><atom:link href="https://semonan.com/en/tags/impl/rss.xml" rel="self" type="application/rss+xml"/><item><title>struct method</title><link>https://semonan.com/en/book/programming/rust/struct-method/</link><pubDate>Thu, 11 Jul 2024 00:00:00 +0000</pubDate><guid>https://semonan.com/en/book/programming/rust/struct-method/</guid><description>&lt;h1 id="struct-method"&gt;struct method&lt;a class="anchor" href="#struct-method"&gt;#&lt;/a&gt;&lt;/h1&gt;
&lt;h2 id="what-is-a-method"&gt;What is a method?&lt;a class="anchor" href="#what-is-a-method"&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;A method is essentially the same as a function, except that it is included within a struct.&lt;br&gt;
Let&amp;rsquo;s learn how to define a method.&lt;br&gt;
In the following example, a &lt;code&gt;Person&lt;/code&gt; struct is defined as &lt;code&gt;struct Person { ~~~ }&lt;/code&gt;.&lt;br&gt;
In &lt;code&gt;impl Person&lt;/code&gt;, &lt;code&gt;impl&lt;/code&gt; stands for implementation.&lt;br&gt;
The functions created inside &lt;code&gt;impl { ~~~ }&lt;/code&gt; are methods.&lt;br&gt;
A method is created with &lt;code&gt;fn speak(self) { ~~~ }&lt;/code&gt;, where &lt;code&gt;self&lt;/code&gt; is taken as the first parameter.&lt;br&gt;
&lt;code&gt;self&lt;/code&gt; refers to the struct itself, &lt;code&gt;struct Person&lt;/code&gt;.&lt;br&gt;
The first parameter of a method must be &lt;code&gt;self&lt;/code&gt;; otherwise, a compile error will occur.&lt;br&gt;
The line &lt;code&gt;println!(&amp;quot;hi, {}&amp;quot;, self.name);&lt;/code&gt; prints &lt;code&gt;self.name&lt;/code&gt;.&lt;br&gt;
Here, &lt;code&gt;self.name&lt;/code&gt; refers to &lt;code&gt;name: String&lt;/code&gt; inside &lt;code&gt;struct Person { name: String, }&lt;/code&gt;.&lt;br&gt;
After creating an instance with &lt;code&gt;let person = Person{ ~~~ };&lt;/code&gt;, you can call the method with &lt;code&gt;person.speak()&lt;/code&gt;.&lt;/p&gt;</description></item></channel></rss>