簡體   English   中英

如何避免 repr 透明包裝器的孤立規則

[英]How to avoid orphan rules for repr transparent wrappers

我的問題是我想要一個透明的包裝器並為它實現Into<underlying> 不幸的是,Rust 的孤兒規則禁止這樣做。 這是一個簡單的例子:

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

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

問題是有什么辦法可以實現嗎? 我正在使用宏為我當前使用的所有類型生成 impl,但它看起來非常笨拙和骯臟。

您可以改為實現 Deref 特性。 Deref 文檔包含以下與您的代碼幾乎相同的示例

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);
}

您可以在常規 impl 塊中實現它:

#[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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM