Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic function to take struct as parameter?

Tags:

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.
}

How can I create a generic some_helper_function function whose parameter can have multiple derived data type like Item2 or Item1?

like image 721
Pramod Avatar asked Mar 22 '26 07:03

Pramod


1 Answers

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.

like image 63
mcarton Avatar answered Mar 24 '26 23:03

mcarton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!