【问题标题】:Rust implement Into trait for Arc<Bar> to Arc<dyn Foo>Rust 实现 Arc<Bar> 到 Arc<dyn Foo> 的 Into 特征
【发布时间】:2020-05-09 20:49:51
【问题描述】:

我正在尝试将实现特征的结构转换为具有相同特征的特征对象。问题是特征对象需要包装在Arc 中,而我无法为Arc 实现Into 特征。由于以下代码未编译:

use std::sync::Arc;

trait Foo { }

struct Bar {}

impl Foo for Bar { }

impl Into<Arc<dyn Foo>> for Arc<Bar> {
    fn into(self) -> Arc<dyn Foo> { self }
}

fn bar_to_foo(bar: Arc<Bar>) -> Arc<dyn Foo> {
    bar.into()
}

这将失败并显示以下编译器消息:

error[E0119]: conflicting implementations of trait `std::convert::Into<std::sync::Arc<(dyn Foo + 'static)>>` for type `std::sync::Arc<Bar>`:
 --> src/lib.rs:9:1
  |
9 | impl Into<Arc<dyn Foo>> for Arc<Bar> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: conflicting implementation in crate `core`:
          - impl<T, U> std::convert::Into<U> for T
            where U: std::convert::From<T>;
  = note: upstream crates may add a new impl of trait `std::convert::From<std::sync::Arc<Bar>>` for type `std::sync::Arc<(dyn Foo + 'static)>` in future versions

error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
 --> src/lib.rs:9:1
  |
9 | impl Into<Arc<dyn Foo>> for Arc<Bar> {
  | ^^^^^------------------^^^^^--------
  | |    |                      |
  | |    |                      `std::sync::Arc` is not defined in the current crate
  | |    `std::sync::Arc` is not defined in the current crate
  | impl doesn't use only types from inside the current crate
  |
  = note: define and implement a trait or new type instead

error: aborting due to 2 previous errors

但是我也不能执行以下操作:

use std::sync::Arc;

trait Foo { }

struct Bar {}

impl Foo for Bar { }

impl Into<dyn Foo> for Bar {
    fn into(self) -> dyn Foo { self }
}

fn bar_to_foo(bar: Arc<Bar>) -> Arc<dyn Foo> {
    bar.into()
}

因为这会导致:

error[E0277]: the size for values of type `(dyn Foo + 'static)` cannot be known at compilation time
 --> src/lib.rs:9:6
  |
9 | impl Into<dyn Foo> for Bar {
  |      ^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `(dyn Foo + 'static)`

我可能遗漏了一些明显的东西,但任何帮助将不胜感激!

【问题讨论】:

    标签: rust traits


    【解决方案1】:

    我是个白痴:

    use std::sync::Arc;
    
    trait Foo { }
    
    struct Bar {}
    
    impl Foo for Bar { }
    
    fn bar_to_foo(bar: Arc<Bar>) -> Arc<dyn Foo> {
        bar
    }
    

    我会展示自己的。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2016-05-29
    相关资源
    最近更新 更多