如何在Rust中添加一个泛型类型实现另一个泛型的约束



我该如何制作这样的东西:

struct FooStruct<A, B> where A : B, B : ?Sized {...}

我搜索了一些类型标记来告诉编译器S必须是一个特性,在Rust文档中搜索了这个模式的一些示例,但找不到其他有同样问题的人。这是我的代码:

trait Factory<S> where S : ?Sized {
fn create(&mut self) -> Rc<S>;
}
trait Singleton<T> {
fn create() -> T;
}
struct SingletonFactory<T> {
instance: Option<Rc<T>>
}
impl<S, T> Factory<S> for SingletonFactory<T> where S : ?Sized, T : S + Singleton<T> {
fn create(&mut self) -> Rc<S> {
if let Some(ref instance_rc) = self.instance {
return instance_rc.clone();
}
let new_instance = Rc::new(T::create());
self.instance = Some(new_instance.clone());
new_instance
}
}

编译器失败,出现以下错误:

--> src/lib.rs:15:57
|
15 | impl<S, T> Factory<S> for SingletonFactory<T> where T : S + Singleton<T> {
|                                                         ^ not a trait

我设法找到了一个答案:std::marker::Unsize<T>特性,尽管在当前版本的Rust(1.14.0)中不是一个稳定的特性。

pub trait Unsize<T> where T: ?Sized { }

可以是";无尺寸的";转换为动态大小的类型。

这比";实现";语义,但这是我从一开始就应该搜索的,因为示例代码中的泛型参数可以是除结构和特征或两个特征(比如大小和未大小的数组)之外的其他东西。

问题中的一般示例可以写成:

struct FooStruct<A, B>
where A: Unsize<B>,
B: ?Sized,
{
// ...
}

我的代码:

impl<S, T> Factory<S> for SingletonFactory<T>
where S: ?Sized,
T: Unsize<S> + Singleton<T>,
{
// ...
}

最新更新