avatarAnkit Tanna

Summary

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3155

Abstract

    }
};

<span class="hljs-keyword">let</span> <span class="hljs-variable">color</span> = Color::<span class="hljs-title function_ invoke__">new</span>(<span class="hljs-number">255</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
<span class="hljs-keyword">let</span> <span class="hljs-variable">rgb</span> = Color::<span class="hljs-title function_ invoke__">rgb</span>(color);

<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{} {} {}"</span>, rgb.<span class="hljs-number">0</span>, rgb.<span class="hljs-number">1</span>, rgb.<span class="hljs-number">2</span>);

}</pre></div><h2 id="e296">Observations:</h2><ol><li>We have a separate declaration section of methods on <code>Color</code> using <code>impl</code> keyword. <code>impl</code> stands for Implementation.</li><li>We define methods inside Color using <code>fn</code> keyword. Just as <code>enum</code> we don’t have comma separation for multiple <code>methods</code>.</li><li>These methods can accept any type of input or can return any type of output including the type they are associated with, i.e. <code>Color</code>.</li><li>We can call these methods using namespace of they type on which they have been defined, i.e. using <code>::</code>. <code>Color::new(255, 0, 0)</code> is an example of how we can call a method.</li></ol><p id="1ec0">So we saw above that we can call the methods using <code>namespace</code> i.e. <code>::</code>. But we can also use chaining mechanism to rather call a method just like we call a method on an object in other languages, using dot <code>.</code>. For e.g. <code>color.new(10, 20, 30)</code>. Rust provides us two more keywords <code>self</code> and <code>Self</code> which allows us to use dot <code>.</code> for making function calls. <code>self</code> and <code>Self</code> are only used inside <code>impl</code>. <code>self</code> means give me one of the types of <code>variants</code> <code>impl</code> is on, in our case, <code>variants</code> of <code>Color</code>. <code>Self</code> with ‘S’ refers to <code>Color</code> itself.</p><h2 id="00c4">self:</h2><ul><li>The lowercase <code>self</code> is a keyword in Rust used within methods to refer to the current instance of the type.</li><li>It is typically used in method definitions and method calls to operate on the instance itself.</li><li>It is a reference to the instance and is used as a parameter for instance methods.</li></ul><h2 id="6250">Self:</h2><ul><li><code>Self</code> is a special keyword used to refer to the current type or the type in which it is used.</li><li>Self is typically used as a return type of methods</li><li>The return type refers to the <code>enum</code> itself.</li></ul><p id="ebeb">Take a look at below code snippet for an example of <code>self</code> and <code>Self</code>:</p><div id="be1a"><pre><span class="hljs-keyword">enum</span> <span class="hljs-title class_">Color</span> { Red, Yellow, Green, Custom { red: <span class="hljs-type">u8</span>, green: <span class="hljs-type">u8</span>, blue: <span class="hljs-type">u8</span> } }

<span class="hljs

Options

-keyword">impl</span> <span class="hljs-title class_">Color</span> { <span class="hljs-comment">// Associated function that creates a custom Color</span> <span class="hljs-keyword">fn</span> <span class="hljs-title function_">custom_color</span>(r: <span class="hljs-type">u8</span>, g: <span class="hljs-type">u8</span>, b: <span class="hljs-type">u8</span>) <span class="hljs-punctuation">-></span> <span class="hljs-keyword">Self</span> { Color::Custom { red: r, green: g, blue: b } }

<span class="hljs-comment">// Method that prints information about the Color</span>
<span class="hljs-keyword">fn</span> <span class="hljs-title function_">describe</span>(&amp;<span class="hljs-keyword">self</span>) {
    <span class="hljs-keyword">match</span> <span class="hljs-keyword">self</span> {
        <span class="hljs-keyword">Self</span>::Red =&gt; {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The color is Red!"</span>);
        }
        <span class="hljs-keyword">Self</span>::Yellow =&gt; {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The color is Yellow!"</span>);
        }
        <span class="hljs-keyword">Self</span>::Green =&gt; {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The color is Green!"</span>);
        }
        <span class="hljs-keyword">Self</span>::Custom { red, green, blue } =&gt; {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Custom color: R={}, G={}, B={}"</span>, red, green, blue);
        }
    }
}

}

<span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() { <span class="hljs-keyword">let</span> <span class="hljs-variable">red_color</span> = Color::Red; <span class="hljs-keyword">let</span> <span class="hljs-variable">custom_color</span> = Color::<span class="hljs-title function_ invoke__">custom_color</span>(<span class="hljs-number">255</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);

red_color.<span class="hljs-title function_ invoke__">describe</span>();
custom_color.<span class="hljs-title function_ invoke__">describe</span>();

}</pre></div><h2 id="b2fa">Observations:</h2><ol><li>We used <code>self</code> keyword as a parameter of <code>describe</code> method.</li><li>This <code>self</code> keyword basically represents all the variants of <code>Color</code> <code>enum</code>.</li><li><code>Self</code> basically referes to <code>Color</code> inside which the methods are declared.</li></ol><p id="9f13">I hope you enjoyed this article on how to write methods in Rust. Please share your feedback in the comments section.</p><p id="63ad">You can subscribe to my newsletter about <b>The Rust Programming Language <a href="https://tinyletter.com/ankittanna"></a></b><a href="https://tinyletter.com/ankittanna">here</a>. You can read about all the articles in this series <a href="https://readmedium.com/the-rust-programming-language-4b22bc717ecc">here</a>.</p></article></body>

The Rust Programming Language

The Rust Programming Language — Pattern Matching — Methods

Rust provides us with a way we can define methods on the an enum namespace. It provides us with impl keyword. Methods allow you to call the lines of code in context of certain namespaces. We use methods when the function calls are associated to a particular type, for e.g. enums. Methods are associated functions called on a instance of particular type.

So we have an enum Color and we want to introduce a method to it. We’ll write 2 methods on the enum Color named rgb and new. So we’ll have 2 methods in the scope of Color.

Let’s take a look at below code snippet:

enum Color {
    Red,
    Yellow,
    Green,
    Custom { red: u8, green: u8, blue: u8 }
}

impl Color {
    fn rgb(color: Color) -> (u8, u8, u8) {
        match color {
            Color::Red => (255, 0, 0),
            Color::Yellow => (255, 255, 0),
            Color::Green => (0, 255, 0),
            Color::Custom { red, green, blue } => (red, green, blue)
        }
    }
    fn new(r: u8, g: u8, b: u8) -> Color {
        Color::Custom { red: r, green: g, blue: b }
    }
}

fn main() {
    let current_color: Color = Color::Green;

    let color_description = match current_color {
        Color::Red => {
            "The color is Red!"
        }
        Color::Yellow => {
            "The color is Yellow!"
        }
        _ => {
            "The color is a different color!"
        }
    };

    let color = Color::new(255, 0, 0);
    let rgb = Color::rgb(color);

    println!("{} {} {}", rgb.0, rgb.1, rgb.2);
}

Observations:

  1. We have a separate declaration section of methods on Color using impl keyword. impl stands for Implementation.
  2. We define methods inside Color using fn keyword. Just as enum we don’t have comma separation for multiple methods.
  3. These methods can accept any type of input or can return any type of output including the type they are associated with, i.e. Color.
  4. We can call these methods using namespace of they type on which they have been defined, i.e. using ::. Color::new(255, 0, 0) is an example of how we can call a method.

So we saw above that we can call the methods using namespace i.e. ::. But we can also use chaining mechanism to rather call a method just like we call a method on an object in other languages, using dot .. For e.g. color.new(10, 20, 30). Rust provides us two more keywords self and Self which allows us to use dot . for making function calls. self and Self are only used inside impl. self means give me one of the types of variants impl is on, in our case, variants of Color. Self with ‘S’ refers to Color itself.

self:

  • The lowercase self is a keyword in Rust used within methods to refer to the current instance of the type.
  • It is typically used in method definitions and method calls to operate on the instance itself.
  • It is a reference to the instance and is used as a parameter for instance methods.

Self:

  • Self is a special keyword used to refer to the current type or the type in which it is used.
  • Self is typically used as a return type of methods
  • The return type refers to the enum itself.

Take a look at below code snippet for an example of self and Self:

enum Color {
    Red,
    Yellow,
    Green,
    Custom { red: u8, green: u8, blue: u8 }
}

impl Color {
    // Associated function that creates a custom Color
    fn custom_color(r: u8, g: u8, b: u8) -> Self {
        Color::Custom { red: r, green: g, blue: b }
    }

    // Method that prints information about the Color
    fn describe(&self) {
        match self {
            Self::Red => {
                println!("The color is Red!");
            }
            Self::Yellow => {
                println!("The color is Yellow!");
            }
            Self::Green => {
                println!("The color is Green!");
            }
            Self::Custom { red, green, blue } => {
                println!("Custom color: R={}, G={}, B={}", red, green, blue);
            }
        }
    }
}

fn main() {
    let red_color = Color::Red;
    let custom_color = Color::custom_color(255, 0, 0);

    red_color.describe();
    custom_color.describe();
}

Observations:

  1. We used self keyword as a parameter of describe method.
  2. This self keyword basically represents all the variants of Color enum.
  3. Self basically referes to Color inside which the methods are declared.

I hope you enjoyed this article on how to write methods in Rust. Please share your feedback in the comments section.

You can subscribe to my newsletter about The Rust Programming Language here. You can read about all the articles in this series here.

Rust
Rustlang
Rust Programming Language
Web Development
Performance
Recommended from ReadMedium