【发布时间】:2020-02-17 18:46:01
【问题描述】:
我正在尝试编写一个通用方法,该方法接受一个返回Serialize 值或Arc<Serialize> 值的函数。我的解决方案是创建一个特征以在需要时解开 Arc 并生成对基础值的引用:
use serde::Serialize;
use std::sync::Arc;
pub trait Unwrapper {
type Inner: Serialize;
fn unwrap(&self) -> &Self::Inner;
}
impl<T> Unwrapper for T
where
T: Serialize,
{
type Inner = T;
fn unwrap(&self) -> &Self::Inner {
self
}
}
impl<T> Unwrapper for Arc<T>
where
T: Serialize,
{
type Inner = T;
fn unwrap(&self) -> &Self::Inner {
self
}
}
fn use_processor<F, O>(processor: F)
where
O: Unwrapper,
F: Fn() -> O,
{
// do something useful processor
}
我收到 E0119 错误,因为 Arc 将来可能会实现 Serialize,就像我启用 serde crate 的功能以允许这样做:
error[E0119]: conflicting implementations of trait `Unwrapper` for type `std::sync::Arc<_>`:
--> src/lib.rs:20:1
|
10 | / impl<T> Unwrapper for T
11 | | where
12 | | T: Serialize,
13 | | {
... |
17 | | }
18 | | }
| |_- first implementation here
19 |
20 | / impl<T> Unwrapper for Arc<T>
21 | | where
22 | | T: Serialize,
23 | | {
... |
27 | | }
28 | | }
| |_^ conflicting implementation for `std::sync::Arc<_>`
我不想这样做,因为我只想在顶层允许Arc,而不是在值内(出于同样的原因,该功能默认情况下不启用)。鉴于此,有没有办法只为Arc 禁用我的第一个impl?还是有更好的解决问题的方法?
【问题讨论】:
-
问题是我无法为取代更通用(第一个)的特征创建“更专业”的 impl(第二个),因此我可以为这个子集提供特殊处理类型 (Arc
) -
谢谢,我想这就是我正在寻找的这段代码,但我想它仍然只在夜间可用。