rust - 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 的东西)。
不知道从这里去哪里!任何帮助,将不胜感激!
解决方案
宏可以工作。(操场)
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);
推荐阅读
- amazon-web-services - 如何在 Docker swarm 中部署 aws-xray-daemon?
- python - 从数据框中绘制图形
- python - Python 字典键对
- node.js - nodemon 卡在“干净退出 - 重新启动前等待更改”。请找到随附的屏幕截图
- google-cloud-firestore - 我们可以使用 Python 脚本或一些 api 调用而不是 UI 来选择 Firestore 原生模式吗?
- sql - 声纳曲。使用 union 解析 CROSS APPLY 中的错误,但一切看起来都不错
- c - 遍历链表做某事
- python - BeautifulSoup:如何从解析的 html 中提取特定元素
- django - 在 PasswordResetView django 中自定义电子邮件设置
- python - 我应该在 kfold 验证设置中在哪里定义 sklearn 模型?