2017-01-15 120 views
3

我怎样才能让这样的工作:如何添加约束一个泛型类型实现了锈另一个泛型类型?

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

我搜索了某种类型的标记告诉编译器S必须是一个特点,搜索这种模式的一些例子锈文件,并不能发现有同样的问题其他人。这里是我的代码:

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 

回答

4

我设法找到一个答案:std::marker::Unsize<T> trait,虽然锈病的当前版本不是稳定的特征(1.14 .0)。

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

类型,可以是“未施胶”发送给动态大小的类型。

这比“implements”语义更广泛,但它是我应该从头开始搜索的内容,因为示例代码中的泛型参数可以是除结构和特征或两个以外的其他内容性状(比如大小和未分级阵列)。

的问题通用例子可以写成:

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

我不知道'Unsize'的,它肯定打开了新的大门! –

+0

是的,它深藏在文档中:)这个RFC提供了一些关于它的信息:https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md。感谢挖'Unsize'很多关于你的帮助:)再次感谢 – Gdow

+0

,SO享受无广告) –

相关问题