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

3
我该如何让这样的东西起作用:
struct FooStruct<A, B> where A : B, B : ?Sized {...}

我在寻找一种类型标记,告诉编译器 S 必须是一个 trait,搜索了 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
1个回答

4
我找到了一个答案: std::marker::Unsize<T> trait,虽然在当前版本的Rust(1.14.0)中不是一个稳定的特性。
pub trait Unsize<T> where T: ?Sized { }

Types that can be "unsized" to a dynamically-sized type.

这个概念比“implements”要广泛,但这才是我一开始应该寻找的,因为示例代码中的通用参数可以是结构体以外的其他内容,也可以是两个trait(比如sized和unsized数组)。

问题中的通用示例可写为:

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>,
{
    // ...
}

我之前不知道 Unsize,它确实为我们打开了新的大门! - Matthieu M.
是的,它被深深地隐藏在文档中 :) 这个 RFC 提供了一些相关信息:https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md。非常感谢您的帮助 :) - Gdow
再次感谢您挖掘出 Unsize,享受无广告的 SO ;) - Matthieu M.
谢谢,太好了 :) - Gdow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接