返回具有关联类型的特征

问题描述 投票:0回答:1
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
    }
}

Playground link

我根据字符串输入返回两个不同的结构AB

[将关联类型指定为占位符时,我得到the type placeholder '_' is not allowed within types on item signatures

generics struct rust traits associated-types
1个回答
1
投票

我相信这里有一个误解; dyn AB<Prop = A>dyn AB<Prop = B>是不同的类型,第一个是动态AB<Prop = A>,第二个是动态AB<Prop = B>。这意味着您不能将泛型和关联类型留给动态方面。

这与未提及关联类型时不同:

fn foo<T: AB>() {
    let my_fn: fn(&T, T::Prop) = T::b;
}

我们访问T::Prop而不是分配它的位置。


[所有类型必须是具体的,并且一个分支上的dyn AB<Prop = A>,而另一个分支上的dyn AB<Prop = B>不是具体的,但是如果将其打包在枚举下,则可能是这样:

enum AOrB {
    A(Box<dyn AB<Prop = A>>),
    B(Box<dyn AB<Prop = B>>),
}
© www.soinside.com 2019 - 2024. All rights reserved.