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
函数,其参数可以具有多个派生数据类型,如Item2
或Item1
。
在你的例子中,Item1
和Item2
之间没有任何关系。而且Rusts泛型不像鸭子类型,就像C ++模板或Python函数一样。
如果你想要一个函数来处理几种类型,那么通常的方法是使它成为通用的,并且有一些特性来定义这些类型的共同点:
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());
}
有a proposal有字段到特征,这将允许你使用通用的item.a
(你仍然必须为每种类型实现特征)。但它已被推迟。这个提案似乎没有太大的收获和一些问题没有得到解决,并且它没有被视为优先事项。