返回具有关联类型的特征 [英] Returning a trait with an associated type
问题描述
struct A;
struct PropA;
struct B;
struct PropB;
trait AB{
type prop;
fn a(&self) -> ();
fn b(&self, p: Self::prop) -> ();
}
impl AB for A{
type prop = PropA;
fn a(&self)->(){}
fn b(&self, p: Self::prop) -> (){}
}
impl AB for B{
type prop = PropB;
fn a(&self)->(){}
fn b(&self, p: Self::prop) -> (){}
}
fn get_a_or_b(s: &str) -> Option<Box<dyn AB<prop=_>>>{
match s{
"a" => Some(Box::new(A)),
"b" => Some(Box::new(B)),
_=> None
}
}
我将基于字符串输入返回两个不同的结构 A
& B
.
I am returning two different structs A
&B
based on a string input.
在将相关类型指定为占位符时,我得到在项目签名上的类型中不允许使用占位符'_'
.
I get the type placeholder '_' is not allowed within types on item signatures
when specifying associated type as placeholder.
推荐答案
我认为这里存在误解; dyn AB< Prop = A>
和 dyn AB< Prop = B>
是不同的类型,第一个是动态的 AB< Prop = A>
>,第二个是动态的 AB< Prop = B>
.这意味着您不能将泛型类型和关联类型留给动态方面.
I believe there's a misconception here; dyn AB<Prop = A>
and dyn AB<Prop = B>
are different types, the first is a dynamic AB<Prop = A>
and the second is a dynamic AB<Prop = B>
. What this means is that you cannot leave generic types and associated types up to the dynamic aspect.
这与未提及关联类型时不同:
This is different than when the associated type is not mentioned:
fn foo<T: AB>() {
let my_fn: fn(&T, T::Prop) = T::b;
}
我们在这里访问 T :: Prop
而不是分配它.
Where we access the T::Prop
instead of assigning it.
所有类型都必须是具体的,并且一个分支上的 dyn AB< Prop = A>
和另一分支上的 dyn AB< Prop = B>
并不具体,但是应该将它包装在枚举下:
All types must be concrete, and dyn AB<Prop = A>
on one branch, and dyn AB<Prop = B>
on another branch is not concrete, but could be should you package it up under an enum:
enum AOrB {
A(Box<dyn AB<Prop = A>>),
B(Box<dyn AB<Prop = B>>),
}
这篇关于返回具有关联类型的特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!