![](/img/trans.png)
[英]Is it possible to create a type alias that has trait bounds on a generic type for a function?
[英]Is it possible to create a generic impl for a trait that works with all but one subset of types?
我正在尝试编写一个通用方法,该方法接受一个返回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
}
由于Arc
将来可能会实现Serialize
,我收到了E0119
错误,就像我启用 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
? 或者有没有更好的方法来解决问题?
您的尝试不起作用,因为不可能有一个特征的重叠实现。
下面试图编写接受泛型方法Serialize
值或Arc
一的Serialize
值。
它利用了Borrow
特性及其对任何 T 的全面实现。
请注意在泛型方法的调用站点上使用 turbo fish 语法。
use std::sync::Arc;
use std::borrow::Borrow;
use serde::Serialize;
#[derive(Serialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn myserialize<T: Borrow<I>, I: Serialize>(value: T) {
let value = value.borrow();
let serialized = serde_json::to_string(value).unwrap();
println!("serialized = {}", serialized);
}
fn main() {
let point = Point { x: 1, y: 2 };
myserialize(point);
let arc_point = Arc::new(Point { x: 1, y: 2 });
myserialize::<_, Point>(arc_point);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.