首页 > 解决方案 > Rust: impl From<_> 用于 usize、u64、u32 等

问题描述

让 S 成为一个结构。我想为所有 uint 类型实现 From 。有没有一种简洁的方法来做到这一点?

例如,我想写这段代码

impl From<S> for usize {
    fn from(s: S) -> usize {
        s.field_a + s.field_b    
    }
}

impl From<S> for u64 {
    fn from(s: S) -> u64 {
        s.field_a + s.field_b    
    }
}

impl From<S> for u32 {
    fn from(s: S) -> u32 {
        s.field_a + s.field_b    
    }
}

...

作为

impl From<S> for uint {
    fn from(s: S) -> uint {
        s.field_a + s.field_b    
    }
}

我的第一个想法是使用特征对所有 uint 进行分组,例如我们如何将特征作为参数传递。这是我的尝试:

use std::ops::Add;

impl From<S> for impl From + Add {
    fn from<T: From + Add>(s: S) -> T {
        T::from(s.field_a) + T::from(s.field_b)
    }
}

但这不起作用并且感觉很笨拙(uint 不仅仅是实现 From 和 Add 的东西)。

不知道从这里去哪里!任何帮助,将不胜感激!

标签: rusttype-conversion

解决方案


宏可以工作。(操场)

struct S {
    field_a: u8,
    field_b: u8,
}

macro_rules! impl_from_s {
    ($($uint_type: ty),*) => {
        $(
            impl From<S> for $uint_type {
                fn from(s: S) -> $uint_type {
                    <$uint_type>::from(s.field_a) + <$uint_type>::from(s.field_b)
                }
            }
        )*
    }
}

impl_from_s!(u8, u16, u32, u64, u128);

推荐阅读