Lifetime Annotation in Rust Traits

RustRustBeginner
Practice Now

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

Introduction

In this lab, we explore the annotation of lifetimes in trait methods, which is similar to functions. It involves annotating lifetimes in the impl block as well. The provided code demonstrates an example where a struct Borrowed has a lifetime annotation, and the Default trait is implemented for it using the annotated lifetime. The main function then creates an instance of Borrowed using the Default::default() method, showcasing the usage of lifetimes in trait methods.

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/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("`Method Syntax`") subgraph Lab Skills rust/variable_declarations -.-> lab-99208{{"`Lifetime Annotation in Rust Traits`"}} rust/integer_types -.-> lab-99208{{"`Lifetime Annotation in Rust Traits`"}} rust/function_syntax -.-> lab-99208{{"`Lifetime Annotation in Rust Traits`"}} rust/expressions_statements -.-> lab-99208{{"`Lifetime Annotation in Rust Traits`"}} rust/method_syntax -.-> lab-99208{{"`Lifetime Annotation in Rust Traits`"}} end

Traits

Annotation of lifetimes in trait methods basically are similar to functions. Note that impl may have annotation of lifetimes too.

// A struct with annotation of lifetimes.
#[derive(Debug)]
struct Borrowed<'a> {
    x: &'a i32,
}

// Annotate lifetimes to impl.
impl<'a> Default for Borrowed<'a> {
    fn default() -> Self {
        Self {
            x: &10,
        }
    }
}

fn main() {
    let b: Borrowed = Default::default();
    println!("b is {:?}", b);
}

Summary

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

Other Rust Tutorials you may like