How to create a trait that requires Drop to be overridden?

Consider a trait which requires a certain cleanup method to be implemented and also ensure that this cleanup is actually performed when an instance is dropped. That we can write something like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>trait MyTrait {
fn cleanup(&self);
}
struct MyStruct;
impl MyTrait for MyStruct {
fn cleanup(&self) {
println!("Cleaning up");
}
}
impl Drop for MyStruct {
fn drop(&mut self) {
<Self as MyTrait>::cleanup(self);
}
}
fn main() {
{
let x = MyStruct;
}
println!("done");
}
</code>
<code>trait MyTrait { fn cleanup(&self); } struct MyStruct; impl MyTrait for MyStruct { fn cleanup(&self) { println!("Cleaning up"); } } impl Drop for MyStruct { fn drop(&mut self) { <Self as MyTrait>::cleanup(self); } } fn main() { { let x = MyStruct; } println!("done"); } </code>
trait MyTrait {
    fn cleanup(&self);
}

struct MyStruct;

impl MyTrait for MyStruct {
    fn cleanup(&self) {
        println!("Cleaning up");
    }
}

impl Drop for MyStruct {
    fn drop(&mut self) {
        <Self as MyTrait>::cleanup(self);
    }
}

fn main() {
    {
        let x = MyStruct;
    }
    println!("done");
}

and it will work, but it does not force the implementation of Drop on MyStruct and it might be easily omitted.
Is there a way to define MyTrait in a way that will ensure or provide a default implementation of drop() calling cleanup()?

11

Here’s a possible solution using a macro:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>mod library {
pub trait MyTraitImpls {
fn cleanup(&self);
}
/// Users are forbidden from implementing this.
#[doc(hidden)]
pub trait __Private {}
/// Implement via `MyTraitImpls` and `impl_my_trait!(...)`
pub trait MyTrait: MyTraitImpls + __Private {}
impl<T: MyTraitImpls + __Private> MyTrait for T {}
#[macro_export]
macro_rules! impl_my_trait {
($name: ident) => {
impl library::__Private for $name {}
impl Drop for $name {
fn drop(&mut self) {
<Self as library::MyTraitImpls>::cleanup(self);
}
}
}
}
}
use crate::library::*;
struct MyStruct;
impl MyTraitImpls for MyStruct {
fn cleanup(&self) {
println!("Cleaning up");
}
}
impl_my_trait!(MyStruct);
</code>
<code>mod library { pub trait MyTraitImpls { fn cleanup(&self); } /// Users are forbidden from implementing this. #[doc(hidden)] pub trait __Private {} /// Implement via `MyTraitImpls` and `impl_my_trait!(...)` pub trait MyTrait: MyTraitImpls + __Private {} impl<T: MyTraitImpls + __Private> MyTrait for T {} #[macro_export] macro_rules! impl_my_trait { ($name: ident) => { impl library::__Private for $name {} impl Drop for $name { fn drop(&mut self) { <Self as library::MyTraitImpls>::cleanup(self); } } } } } use crate::library::*; struct MyStruct; impl MyTraitImpls for MyStruct { fn cleanup(&self) { println!("Cleaning up"); } } impl_my_trait!(MyStruct); </code>
mod library {
    pub trait MyTraitImpls {
        fn cleanup(&self);
    }

    /// Users are forbidden from implementing this.
    #[doc(hidden)]
    pub trait __Private {}
    
    /// Implement via `MyTraitImpls` and `impl_my_trait!(...)`
    pub trait MyTrait: MyTraitImpls + __Private {}
    
    impl<T: MyTraitImpls + __Private> MyTrait for T {}
    
    #[macro_export]
    macro_rules! impl_my_trait {
        ($name: ident) => {
            impl library::__Private for $name {}
        
            impl Drop for $name {
                fn drop(&mut self) {
                    <Self as library::MyTraitImpls>::cleanup(self);
                }
            }
        }
    }
}

use crate::library::*;

struct MyStruct;
impl MyTraitImpls for MyStruct {
    fn cleanup(&self) {
        println!("Cleaning up");
    }
}
impl_my_trait!(MyStruct);

The user could bypass this by impl library::__Private for MyStruct {} but at least you can’t do that accidentally.

You could write this as a procedural macro (#[derive(MyTrait)]) to make it more idiomatic.

I have converged to an implementation which is arguably over-cautious, but seems to provide the required functionality. It requires a wrapper type though. Here is an example of generic “mapping” API, where the implementer is required to provide the code for performing the mapping and the code for unmapping (cleanup in the original question).

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>mod mapping {
use std::marker::PhantomData;
pub struct Token {
_priv: PhantomData<()>,
}
pub trait MappingTrait
{
type Params;
fn map(params: Self::Params, _t: Token) -> Self;
fn unmap(&self, _t: Token);
}
pub struct Mapping<M: MappingTrait>
{
mapping_impl: M,
}
impl <M: MappingTrait> Mapping<M> {
pub fn new(params: M::Params) -> Self {
Self {
mapping_impl: M::map(params, Token {_priv: PhantomData} ),
}
}
}
impl<M: MappingTrait> Drop for Mapping<M> {
fn drop(&mut self) {
self.mapping_impl.unmap(Token {_priv: PhantomData});
}
}
}
</code>
<code>mod mapping { use std::marker::PhantomData; pub struct Token { _priv: PhantomData<()>, } pub trait MappingTrait { type Params; fn map(params: Self::Params, _t: Token) -> Self; fn unmap(&self, _t: Token); } pub struct Mapping<M: MappingTrait> { mapping_impl: M, } impl <M: MappingTrait> Mapping<M> { pub fn new(params: M::Params) -> Self { Self { mapping_impl: M::map(params, Token {_priv: PhantomData} ), } } } impl<M: MappingTrait> Drop for Mapping<M> { fn drop(&mut self) { self.mapping_impl.unmap(Token {_priv: PhantomData}); } } } </code>
mod mapping {
    use std::marker::PhantomData;
    
    pub struct Token {
        _priv: PhantomData<()>,
    }

    pub trait MappingTrait
    {
        type Params;
        fn map(params: Self::Params, _t: Token) -> Self;
        fn unmap(&self, _t: Token);
    }

    pub struct Mapping<M: MappingTrait>
    {
        mapping_impl: M,
    }
    
    impl <M: MappingTrait> Mapping<M> {
        pub fn new(params: M::Params) -> Self {
            Self {
                mapping_impl: M::map(params, Token {_priv: PhantomData} ),
            }
        }
    }

    impl<M: MappingTrait> Drop for Mapping<M> {
        fn drop(&mut self) {
            self.mapping_impl.unmap(Token {_priv: PhantomData});
        }
    }
}

The required implementation of MappingTrait requires the map and unmap methods to use a parameter of Token type, which is not constructable outside of the module, so the implemented type cannot be used “directly” even in the module it is implemented in.
Then there is a wrapper type Mapping<M: MappingTrait>, which can internally construct Token and use the provided API. It is also implementing Drop, where unmap of the wrapped type is called.

Here is the example usage:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>use mapping::*;
struct MyMappingImpl
{
some_data: usize,
}
impl MappingTrait for MyMappingImpl {
type Params = usize;
fn map(params: usize, _t: Token) -> Self {
println!("Mapping {}...", params);
MyMappingImpl {some_data: params}
}
fn unmap(&self, _t: Token) {
println!("Unmapping {}...", self.some_data);
}
}
fn main() {
{
let _m: Mapping<MyMappingImpl> = Mapping::new(42);
}
println!("Done");
}
</code>
<code>use mapping::*; struct MyMappingImpl { some_data: usize, } impl MappingTrait for MyMappingImpl { type Params = usize; fn map(params: usize, _t: Token) -> Self { println!("Mapping {}...", params); MyMappingImpl {some_data: params} } fn unmap(&self, _t: Token) { println!("Unmapping {}...", self.some_data); } } fn main() { { let _m: Mapping<MyMappingImpl> = Mapping::new(42); } println!("Done"); } </code>
use mapping::*;

struct MyMappingImpl
{
    some_data: usize,
}

impl MappingTrait for MyMappingImpl {
    type Params = usize;
    
    fn map(params: usize, _t: Token) -> Self {
        println!("Mapping {}...", params);
        MyMappingImpl {some_data: params}
    }
    
    fn unmap(&self, _t: Token) {
        println!("Unmapping {}...", self.some_data);
    }
}


fn main() {
    {
        let _m: Mapping<MyMappingImpl> = Mapping::new(42);
    }
    println!("Done");
}

This code will print

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Mapping 42...
Unmapping 42...
Done
</code>
<code>Mapping 42... Unmapping 42... Done </code>
Mapping 42...
Unmapping 42...
Done

Link to Playground

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật