首页 > 解决方案 > 如何从 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 个问题:

  1. 我不知道如何实现From它的要求
  2. 我不想创建临时向量...肯定有一些零成本抽象允许我传递转换后的数组

标签: rust

解决方案


推荐阅读