【问题标题】:Heterogenous containers in Rust for a graphRust 中用于图的异构容器
【发布时间】:2020-05-24 21:36:58
【问题描述】:

我是一名学习 Rust 的 C++ 程序员,我的主要用例之一是基于图形的计算引擎。在我的图中,我存储了一个同质类型,然后我从中派生出一个更具体的类型,例如在 C++ 中

class BaseNode {
  public:
    BaseNode(std::vector<std::shared_ptr<BaseNode>>& parents);
    virtual ~BaseNode() = default;

    virtual void update(); 
    const std::vector<std::shared_ptr<BaseNode>>& parents() const;
    ...
};

template<typename T>
class TypedNode<T> : public BaseNode {
  public:
    const T& value() const { return value_; }

    ...
  private:
    T value_;
}

这个想法是遍历图并在每个节点上调用update()。该节点知道它的每个父“真实类型”是什么,因此在其update() 中可以执行static_cast&lt;TypedNode&lt;DataBlob&gt;&gt;(parents()[0]) 之类的操作。

如何在 Rust 中实现这样的目标?

我想过有这样的设计:

trait BaseNode {
    fn parents(&self) -> &Vec<dyn BaseNode>;
}

trait TypedNode<T>: BaseNode {
    fn value(&self) -> &T;
}

但我读到我无法将“特征对象”从 BaseNode 转换为 TypedNode&lt;T&gt;。 (或者我可以使用unsafe 以某种方式做到这一点吗?)。我认为另一种选择是拥有一个将数据存储在Any 中的结构,然后进行转换,但这会产生一些运行时成本吗?

【问题讨论】:

标签: rust graph-theory container-data-type


【解决方案1】:

如果所有节点的父节点都具有相同的类型,那么您可以使用该方法:

trait BaseNode {
    type Parent: BaseNode;
    fn parents(&self) -> &[Self::Parent];
}

trait TypedNode<P: BaseNode>: BaseNode<Parent = P> {
    type ValueType;
   fn value(&self) -> &Self::ValueType;
}

Rust playground

我不确定我是否理解您的问题。如果它不适合你,请告诉我。

【讨论】:

    猜你喜欢
    • 2011-12-09
    • 2022-12-10
    • 2018-08-21
    • 2015-02-24
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多