简体   繁体   中英

How to avoid orphan rules for repr transparent wrappers

My problem is I want to have a transparent wrapper and implemented Into<underlying> for it. Unfortunately, rust's orphan rules forbid it. Here is a simple example:

#[repr(transparent)]
pub struct MyWrapper<T>(pub T);

impl<T> Into<T> for MyWrapper<T> {
    fn into(self) -> T {
        self.0
    }
}

The question is is there any way I can implement it? I'm using macro to generate impl for all types I'm currently using but it looks very awkward and dirty.

You can implement the Deref trait instead. The Deref docs contain the following example which is almost identical to your code:

use std::ops::Deref;

struct DerefExample<T> {
    value: T
}

impl<T> Deref for DerefExample<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

fn main() {
    let x = DerefExample { value: 'a' };
    assert_eq!('a', *x);
}

You can implement it in a regular impl block:

#[repr(transparent)]
pub struct MyWrapper<T>(pub T);

impl<T> MyWrapper<T> {
    pub fn into(self) -> T {
        self.0
    }
}

fn main() {
    let wrapped : MyWrapper<f32> = MyWrapper::<f32>(3.4f32);
    let unwrapped : f32 = wrapped.into();
    println!("{}", unwrapped);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM