我是从Java,C#,C ++和有限的C知识的背景来研究Rust的。我之所以选择Rust是因为我认为设计模式和类型安全性将极大地改善我的最终产品。我不太擅长写这类东西,因此我列出了我的目标和遇到的问题。
目标:
Vec
或任何存储实现共同特征的不同对象的列表。
我不确定存储具有泛型特征的泛型类型的最佳/最安全方法是什么,同时仍然具有我想要的灵活性。
// 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.
}
}