我怎么能做这样的工作:
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
}
}
编译器失败,错误如下:
<span style="color:#212529"><code style="margin-left:2px"> --> src/lib.rs:15:57
|
15 | impl<S, T> Factory<S> for SingletonFactory<T> where T : S + Singleton<T> {
| ^ not a trait
</code></span>
最佳答案
我找到了一个答案:std::marker::Unsize<T>
trait,尽管在当前版本的Rust(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>,
{
// ...
}