rust - Rust实现Arc <Bar>到Arc <dyn Foo>的特征

标签 rust traits

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

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)`

我可能缺少明显的东西,但是任何帮助将不胜感激!

最佳答案

我是个白痴:

use std::sync::Arc;

trait Foo { }

struct Bar {}

impl Foo for Bar { }

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

我将展示自己。

关于rust - Rust实现Arc <Bar>到Arc <dyn Foo>的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59880977/

相关文章:

可以拥有或借用其内容的 Rust 泛型类型

rust - 为实现特定类型的 trait 的泛型类型实现 trait

rust - 无法将特征方法纳入范围

rust - 在 Rust 中访问属性后调用 &mut self 上的方法

rust - 从Rust中的函数返回异步函数

rust - 根据构建目标,在fltk-rs中使用fltk::osxMenuBar或MenuBar

rust - 特征边界 `std::io::Write + ' static: std::marker::Sized` 不满足,当传递闭包时

enums - 在枚举中使用特征作为类型

serialization - 将字符串或枚举放入 LMDB

rust - 将 Ref<Box<dyn Any>> 向下转换为 Ref<Box<T>> 时处理向下转换错误