存储结构而不在Rust中定义泛型类型

时间:2019-11-12 23:41:49

标签: generics rust traits

我是从Java,C#,C ++和有限的C知识的背景来研究Rust的。我之所以选择Rust是因为我认为设计模式和类型安全性将极大地改善我的最终产品。我不太擅长写这类东西,因此我列出了我的目标和遇到的问题。

目标:

  • 我想要一个Vec或任何存储实现共同特征的不同对象的列表。
    • 特征有两种通用类型,由实现它的对象定义。
  • 列表中存储的每个对象都是唯一的,这意味着该对象将具有为实现trait定义的唯一对象。
  • 每个唯一对象只能在列表中一次。
  • 我想跟踪与每个对象关联的通用类型。这既不是我当前的问题,也不是我现在担心这个细节,但是我不会拒绝对此的建议。

我不确定存储具有泛型特征的泛型类型的最佳/最安全方法是什么,同时仍然具有我想要的灵活性。

// common functions in trait that use A and B.
pub trait Common<A, B> {
    fn common_behavior_one(a: A) {}
    fn common_behavior_two(b: B) {}
}

// these are example objects and there would be many more sets like this
struct objectA {}
struct objectB {}
struct CommonObject {} // stores list of objectA's and consumes objectB's

impl Common<objectA, objectB> for CommonObject {
    fn common_behavior_one(a: objectA) {}
    fn common_behavior_two(b: objectB) {}
}

//this is where my problem starts
struct Manager {
    // i would like this to accept any Object with the Common trait implemented
    // regardless of what the generics for the trait are.
    objects: Vec<Box<impl Common>>, // problem
}

impl Manager {
    pub fn add_object<A, B>(&mut self, _object: Box<Common<A, B>>) { // potential problem
        // add _object to vec
    }

    pub fn remove_object<A, B>(&mut self, _object: Box<Common<A, B>>) { // potential problem
        // remove _object from vec
    }

    pub fn get_object() {} // not sure about how im going to do this.

    pub fn pass_to_object<B>(&mut self, _struct: Box<B>) { // potential problem
        // pass _struct(B type) into common where it will be consumed.
    }
}

0 个答案:

没有答案