Rust Lifetime Coercion Exploration

RustRustBeginner
Practice Now

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

Introduction

In this lab, the concept of coercion in Rust is explored, where a longer lifetime can be coerced into a shorter one to enable functionality within a specific scope. This can occur through inferred coercion by the Rust compiler or by declaring a lifetime difference using syntax such as <'a: 'b, 'b>.

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/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") 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`") subgraph Lab Skills rust/variable_declarations -.-> lab-99210{{"`Rust Lifetime Coercion Exploration`"}} rust/integer_types -.-> lab-99210{{"`Rust Lifetime Coercion Exploration`"}} rust/type_casting -.-> lab-99210{{"`Rust Lifetime Coercion Exploration`"}} rust/function_syntax -.-> lab-99210{{"`Rust Lifetime Coercion Exploration`"}} rust/expressions_statements -.-> lab-99210{{"`Rust Lifetime Coercion Exploration`"}} end

Coercion

A longer lifetime can be coerced into a shorter one so that it works inside a scope it normally wouldn't work in. This comes in the form of inferred coercion by the Rust compiler, and also in the form of declaring a lifetime difference:

// Here, Rust infers a lifetime that is as short as possible.
// The two references are then coerced to that lifetime.
fn multiply<'a>(first: &'a i32, second: &'a i32) -> i32 {
    first * second
}

// `<'a: 'b, 'b>` reads as lifetime `'a` is at least as long as `'b`.
// Here, we take in an `&'a i32` and return a `&'b i32` as a result of coercion.
fn choose_first<'a: 'b, 'b>(first: &'a i32, _: &'b i32) -> &'b i32 {
    first
}

fn main() {
    let first = 2; // Longer lifetime

    {
        let second = 3; // Shorter lifetime

        println!("The product is {}", multiply(&first, &second));
        println!("{} is the first", choose_first(&first, &second));
    };
}

Summary

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

Other Rust Tutorials you may like