Implement Generic Double Deallocation Trait

RustRustBeginner
Practice Now

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

Introduction

In this lab, a generic DoubleDrop trait is defined, which includes a double_drop method that allows a type to deallocate itself and an input parameter.

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/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/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`") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("`Traits for Operator Overloading`") subgraph Lab Skills rust/variable_declarations -.-> lab-99347{{"`Implement Generic Double Deallocation Trait`"}} rust/function_syntax -.-> lab-99347{{"`Implement Generic Double Deallocation Trait`"}} rust/expressions_statements -.-> lab-99347{{"`Implement Generic Double Deallocation Trait`"}} rust/method_syntax -.-> lab-99347{{"`Implement Generic Double Deallocation Trait`"}} rust/traits -.-> lab-99347{{"`Implement Generic Double Deallocation Trait`"}} rust/operator_overloading -.-> lab-99347{{"`Implement Generic Double Deallocation Trait`"}} end

Traits

Of course traits can also be generic. Here we define one which reimplements the Drop trait as a generic method to drop itself and an input.

// Non-copyable types.
struct Empty;
struct Null;

// A trait generic over `T`.
trait DoubleDrop<T> {
    // Define a method on the caller type which takes an
    // additional single parameter `T` and does nothing with it.
    fn double_drop(self, _: T);
}

// Implement `DoubleDrop<T>` for any generic parameter `T` and
// caller `U`.
impl<T, U> DoubleDrop<T> for U {
    // This method takes ownership of both passed arguments,
    // deallocating both.
    fn double_drop(self, _: T) {}
}

fn main() {
    let empty = Empty;
    let null  = Null;

    // Deallocate `empty` and `null`.
    empty.double_drop(null);

    //empty;
    //null;
    // ^ TODO: Try uncommenting these lines.
}

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