Rust Method Usage Demonstration

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, the usage of methods in Rust is demonstrated.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/DataStructuresandEnumsGroup(["`Data Structures and Enums`"]) rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/BasicConceptsGroup -.-> rust/mutable_variables("`Mutable Variables`") rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/DataTypesGroup -.-> rust/type_casting("`Type Conversion and Casting`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("`Method Syntax`") rust/AdvancedTopicsGroup -.-> rust/traits("`Traits`") subgraph Lab Skills rust/variable_declarations -.-> lab-99206{{"`Rust Method Usage Demonstration`"}} rust/mutable_variables -.-> lab-99206{{"`Rust Method Usage Demonstration`"}} rust/integer_types -.-> lab-99206{{"`Rust Method Usage Demonstration`"}} rust/type_casting -.-> lab-99206{{"`Rust Method Usage Demonstration`"}} rust/function_syntax -.-> lab-99206{{"`Rust Method Usage Demonstration`"}} rust/expressions_statements -.-> lab-99206{{"`Rust Method Usage Demonstration`"}} rust/method_syntax -.-> lab-99206{{"`Rust Method Usage Demonstration`"}} rust/traits -.-> lab-99206{{"`Rust Method Usage Demonstration`"}} end

Methods

Methods are annotated similarly to functions:

struct Owner(i32);

impl Owner {
    // Annotate lifetimes as in a standalone function.
    fn add_one<'a>(&'a mut self) { self.0 += 1; }
    fn print<'a>(&'a self) {
        println!("`print`: {}", self.0);
    }
}

fn main() {
    let mut owner = Owner(18);

    owner.add_one();
    owner.print();
}

Summary

Congratulations! You have completed the Methods lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like