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
之间没有关系,并且 Rust 的泛型不是鸭子类型,如 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
(您仍然需要为每种类型实现特征)。但它已被推迟。看来这个提案收获太少,而且有些问题没有解决,没有被视为优先事项。
关于rust - 以结构作为参数的通用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52129713/