将struct作为生锈参数的通用函数

问题描述 投票:0回答:1
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

rust
1个回答
0
投票

在你的例子中,Item1Item2之间没有任何关系。而且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(你仍然必须为每种类型实现特征)。但它已被推迟。这个提案似乎没有太大的收获和一些问题没有得到解决,并且它没有被视为优先事项。

© www.soinside.com 2019 - 2024. All rights reserved.