引用相同类型但具有任何具体类型的泛型结构 [英] Generic struct with a reference to the same type but with any concrete type

查看:86
本文介绍了引用相同类型但具有任何具体类型的泛型结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意图是创建一个结构,该结构包含对另一个相似类型的引用,但具有不同的泛型以用作链接对象链.

My intention is to create a struct that holds a reference to another one of a similar type, but with different generics to be used as a chain of linked objects.

问题是不允许使用_占位符编写此代码:

The problem is that writing this using the _ placeholder is not allowed:

the type placeholder `_` is not allowed within types on item
signatures

E0121

我不能简单地给我的结构另一个类型参数,因为被引用的对象也可以引用另一个对象,依此类推.这将导致大量类型参数,这是不实际的.

I cannot simply give my struct another type parameter since the referenced object may reference another object too, and so on. This would lead to a very large number of type parameters, which is not practical.

我想找到一种方法来更改此实现以使其起作用:

I would like to find a way to change this implementation to make it work:

// The type parameters are:
// O: this Router's data type
// B: The parent router's data type
pub struct DataRouter<'a, O, B = O>
where
    O: 'a,
    B: 'a,
{
    parent: Option<&'a DataRouter<'a, B, _>>, // Here the problem `_`
    range: Option<Range<usize>>,
    data: Option<O>,
}

我不能像在将参数添加到结构中那样简单地在此处放置参数,这将导致添加类型参数的无限循环.

I can't simply put a parameter here as I would've to add it to the struct, which then would cause the same infinite loop of adding a type parameter.

是否可以保存对具有B数据类型的DataRouter的引用,而该引用本身具有对具有未知数据类型的父DataRouter的引用?该结构只需要知道直接父级数据类型,而不必知道第二个父级数据类型.

Is there a way to hold a reference to a DataRouter with B data type which itself holds a reference to a parent DataRouter with an unknown data type? The struct has to know only the direct parent data type, not the one of the second parent.

如果无法解决此问题,您可以建议其他可行的实现方式吗?

If this cannot be fixed, can you suggest a different implementation that could work?

推荐答案

由于您不必(实际上也不能)关心父级的父级类型,因此可以通过特征引入抽象:

Since you don't (and indeed cannot) care about the type of the parent's parent, introduce abstraction through a trait:

trait Parent {}

struct Nil;
impl Parent for Nil {}

pub struct DataRouter<'a, T, P>
where
    P: 'a,
{
    parent: Option<&'a P>,
    data: Option<T>,
}

impl<'a, T, P> Parent for DataRouter<'a, T, P> {}

fn main() {
    let a = DataRouter {
        parent: None::<&'static Nil>,
        data: Some(true),
    };
    let b = DataRouter {
        parent: Some(&a),
        data: Some(42),
    };
    let c = DataRouter {
        parent: Some(&b),
        data: Some("moo"),
    };
}

这篇关于引用相同类型但具有任何具体类型的泛型结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆