BoxOrMutRef来自dyn特性的转换

时间:2020-05-18 20:06:10

标签: rust traits

我想实现一个枚举,该枚举包含Box或一个可变引用,该引用应可从这两个中的任何一个转换而来:

pub enum BoxOrMutRef<'a, T: ?Sized + 'a> {
    Boxed(Box<T>),
    MutRef(&'a mut T),
}

impl<'a, T: ?Sized + 'a> From<&'a mut T> for BoxOrMutRef<'a, T> {
    fn from(v: &'a mut T) -> BoxOrMutRef<'a, T> {
        BoxOrMutRef::MutRef(v)
    }
}

impl<'a, T> From<T> for BoxOrMutRef<'a, T> {
    fn from(v: T) -> BoxOrMutRef<'a, T> {
        BoxOrMutRef::Boxed(Box::new(v))
    }
}

当我尝试将这些转换功能用于dyn特征时...

trait MyTrait {}

fn test1<'a>(v: impl Into<BoxOrMutRef<'a, dyn MyTrait>>) {}

struct MyStruct {}

impl MyTrait for MyStruct {}

fn main() {
    let mut v = MyStruct {};
    test1(&mut v);
    test1(v);
}

Playground

它失败并显示:

error[E0277]: the trait bound `BoxOrMutRef<'_, dyn MyTrait>: std::convert::From<&mut MyStruct>` is not satisfied
  --> src/main.rs:28:5
   |
20 | fn test1<'a>(v: impl Into<BoxOrMutRef<'a, dyn MyTrait>>) {}
   |    -----             ---------------------------------- required by this bound in `test1`
...
28 |     test1(&mut v);
   |     ^^^^^ the trait `std::convert::From<&mut MyStruct>` is not implemented for `BoxOrMutRef<'_, dyn MyTrait>`
   |
   = help: the following implementations were found:
             <BoxOrMutRef<'a, T> as std::convert::From<&'a mut T>>
             <BoxOrMutRef<'a, T> as std::convert::From<T>>
   = note: required because of the requirements on the impl of `std::convert::Into<BoxOrMutRef<'_, dyn MyTrait>>` for `&mut MyStruct`

error[E0277]: the trait bound `BoxOrMutRef<'_, dyn MyTrait>: std::convert::From<MyStruct>` is not satisfied
  --> src/main.rs:29:5
   |
20 | fn test1<'a>(v: impl Into<BoxOrMutRef<'a, dyn MyTrait>>) {}
   |    -----             ---------------------------------- required by this bound in `test1`
...
29 |     test1(v);
   |     ^^^^^ the trait `std::convert::From<MyStruct>` is not implemented for `BoxOrMutRef<'_, dyn MyTrait>`
   |
   = help: the following implementations were found:
             <BoxOrMutRef<'a, T> as std::convert::From<&'a mut T>>
             <BoxOrMutRef<'a, T> as std::convert::From<T>>
   = note: required because of the requirements on the impl of `std::convert::Into<BoxOrMutRef<'_, dyn MyTrait>>` for `MyStruct`

使用test1(&mut v as &mut dyn MyTrait)可行,但是我想避免在此显式强制转换。我如何更改我的From实现以允许这些转换?

0 个答案:

没有答案