Reputation: 652
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.
}
How can I create a generic some_helper_function
function whose parameter can have multiple derived data type like Item2
or Item1
?
Upvotes: 3
Views: 2413
Reputation: 29981
In your example, there is no relationship between Item1
and Item2
, and Rust's generics are not duck-typed, like C++ templates or Python functions are.
If you want a function to work on several types, the way to go is usually to make it generic, and have some trait that defines what those types have in common:
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());
}
There has been a proposal to had fields to traits, which would let you use item.a
from a generic (you would still have to implement the trait for each type). But it has been postponed. It seems that there was too little gain and some questions unresolved with this proposal, and that it was not seen as a priority.
Upvotes: 5