gpt4 book ai didi

rust - 函数中通用类型的访问字段

转载 作者:行者123 更新时间:2023-12-03 11:25:20 24 4
gpt4 key购买 nike

我花了最后4天的时间试图弄清楚这一点,但我真的很坚持。基本上,我有大量类似的结构,都包含一个特定的字段。让我们将其称为u32类型的data:

struct A {
data: u32,
}

struct B {
data: u32
}

...

struct N {
data: u32
}
我需要做的是在这些结构外部编写一个函数,该函数采用通用类型(即那些结构之一)对字段执行一些操作并返回值。基本上遵循以下原则:
fn some_manipulation<T>(st: &T) -> u32 {
st.data * 10
}
就目前而言,这是不可能的,因为 data类型上没有 T字段。另一件事是我无法修改结构。有一个明智的方法来实现这一目标吗?

最佳答案

因此,正如@Netwave所指出的那样,要使其正常工作,您需要一个some_manipulation将用于访问data字段的特征,但是要为所有类型实现此特征,您可以使用自定义宏。
Playground
我定义了宏,使其看起来像impl_BorrowData!{u32, [A, B, N]}(其中第一个参数是data字段的类型,然后是一个结构列表),但是宏足够灵活,您可以根据需要使它看起来像。

trait BorrowData {
type Output;
fn borrow_data(&self) -> &Self::Output;
}

macro_rules! impl_BorrowData {
($out:ty, [$($t:ty),+]) => {
$(impl BorrowData for $t {
type Output = $out;
fn borrow_data(&self) -> &Self::Output {
&self.data
}
})*
}
}

impl_BorrowData!{u32, [A, B, N]} // first the output type <u32>, then names of structs

fn some_manipulation<T: BorrowData<Output=u32>>(st: &T) -> u32 {
st.borrow_data() * 10
}

fn main() {
let a = A { data: 2 };
println!("{}", some_manipulation(&a));
let b = B { data: 50 };
println!("{}", some_manipulation(&b));
}

关于rust - 函数中通用类型的访问字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64965194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com