rust - 如何从 Rust 获得自动转换为特征?
问题描述
我有一个结构Object
,我有很多实现From
(包括isize
和&str
)。我从这篇Into
被描述为“天才”的文章中了解到,事情可以为我自动转换。我已经整合了人们提出的建议,并在操场上做了一些独立的东西,但它仍然会出现一些错误。
#[derive(Copy,Clone)]
pub union Object {
d:f64,
i:isize,
}
impl From<isize> for Object {
fn from(i:isize) -> Self {
Object{i}
}
}
impl From<f64> for Object {
fn from(d:f64) -> Self {
Object{d}
}
}
pub fn old_convert(foo: Object, _elements: &[Object]) -> Object {
foo
}
pub fn new_convert<'a,T>(foo: impl Into<Object>, elements: &'a [T]) -> Object
where
&'a T: Into<Object>,
Object: From<T>,
{
let mut el = Vec::new();
for o in elements.iter() {
el.push(o.into())
}
old_convert(foo.into(),&el)
}
#[test]
fn testOldConvert() {
old_convert(Object::from(42), &[Object::from(3.1415)]);
}
#[test]
fn testNewConvert() {
new_convert(42, &[3.1415]);
}
所以你可以看到我目前在做什么。我不想Object::from(...)
在使用我的功能时包含所有内容。有 1 个错误和 1 个问题:
- 我不知道如何实现
From
它的要求 - 我不想创建临时向量...肯定有一些零成本抽象允许我传递转换后的数组
解决方案
推荐阅读
- office-js - 为什么我不能在网络服务器上托管 manifest.xml?
- linq - 如何使用实体框架检索父子关系数据并对其进行分页/过滤/排序
- python - 如何在 Mac 上安装 pocketsphinx
- javascript - 无法获取“id”元素
- hashtable - 为什么 marco "ZVAL_COPY_VALUE(z,v)" 似乎在 PHP Internal 中无法正常工作?
- python - 如何在 Python Web 自动化中添加多个代理
- c# - 我必须找到隐藏在 3 行文本中的 4 位 PIN 码
- c# - CORS 策略已阻止访问 fetch - Blazor 客户端 Web 程序集
- boolean - 如何证明 (x+y)(x'+z)(y+z) = (x+y)(x'+z)
- python - Django Group By ManyToManyField 的所有组合