如何为我不拥有的类型实现我不拥有的特征? [英] How do I implement a trait I don't own for a type I don't own?

查看:39
本文介绍了如何为我不拥有的类型实现我不拥有的特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 Vec 实现 Shl 特性,代码如下.这会使 vec <<4 可能,这对 vec.push(4) 来说是很好的糖.

使用 std::ops::Shl;实施<T>Shl T对于 Vec T{类型输出=Vec T ;fn shl(&self, elem: &T) ->Vec T{self.push(*elem);*自己}}fn 主(){让 v = vec![1, 2, 3];v<<4;}

编译失败,错误如下:

<块引用>

不能提供一个扩展实现,其中 trait 和 type 都没有在这个 crate 中定义 [E0117]

<块引用>

类型参数 T 必须用作某些本地类型的类型参数(例如 MyStruct);只能为类型参数实现当前 crate 中定义的特征 [E0210]

据我所知,我必须修补 stdlib,更具体地说是 collections::vec 板条箱.有没有其他方法可以改变这段代码编译成功?

解决方案

虽然您不能完全做到这一点,但通常的解决方法是将您想要的类型包装在您自己的类型中并在其上实现 trait.

>

使用 somecrate::FooType;使用 somecrate::BarTrait;struct MyType(FooType);impl BarTrait for MyType {fn bar(&self) {//在这里使用 `self.0`}}

I wanted to implement the Shl trait for Vec, the code is below. This would make things like vec << 4 possible, which would be nice sugar for vec.push(4).

use std::ops::Shl;

impl<T> Shl<T> for Vec<T> {
    type Output = Vec<T>;

    fn shl(&self, elem: &T) -> Vec<T> {
        self.push(*elem);
        *self
    }
}

fn main() {
    let v = vec![1, 2, 3];
    v << 4;
}

The compilation fails with the following error:

cannot provide an extension implementation where both trait and type are not defined in this crate [E0117]

or

type parameter T must be used as the type parameter for some local type (e.g. MyStruct<T>); only traits defined in the current crate can be implemented for a type parameter [E0210]

As I understand it, I'd have to patch the stdlib, more specifically the collections::vec crate. Is there another way to change this code to compile successfully?

解决方案

While you can't do that exactly, the usual workaround is to just wrap the type you want in your own type and implement the trait on that.

use somecrate::FooType;
use somecrate::BarTrait;

struct MyType(FooType);

impl BarTrait for MyType {
    fn bar(&self) {
        // use `self.0` here
    }
}

这篇关于如何为我不拥有的类型实现我不拥有的特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆