在rust中将struct作为参数的泛型函数

时间:2018-09-01 15:42:42

标签: rust

struct Item1 {
    a: u32
}

struct Item2 {
    a: u32,
    b: u32,
}

fn some_helper_function(item: Item1) {
    // Basically `item` could be of type `Item1` or `Item2`.
    // How I create generic function to take any one of them?
    // Some implementation goes here.
}

如何创建通用的some_helper_function函数,该函数的参数可以具有多个派生数据类型,例如Item2Item1

1 个答案:

答案 0 :(得分:0)

在您的示例中,EventItem1之间没有关系。而且Rusts泛型不是C ++模板或Python函数那样的鸭子类型。

如果您希望函数可以在几种类型上使用,通常的方法是使其具有通用性,并具有一些特征来定义这些类型的共同点:

Item2

已经有a proposal个字段具有特征,这将使您可以使用泛型中的trait HasA { fn get_a(&self) -> u8; } impl HasA for Item1 { fn get_a(&self) -> u8 { self.a } } impl HasA for Item2 { fn get_a(&self) -> u8 { self.a } } fn some_helper_function<T: HasA>(item: T) { println!("The value of `item.a` is {}", item.get_a()); } (您仍然必须为每种类型实现特征)。但这已被推迟。这项提议似乎没有太多收获,还存在一些问题尚未解决,因此它不被视为优先事项。

相关问题