impl convert::From for (mutable) reference



我正在尝试为我想作为可变引用获取的类型实现From,所以我将其插入&mut TheType,但是我如何正确调用from?我执行的尝试失败了,因为它尝试进行反射(来自 TheType 的类型(或无法(或不知道如何(从类型&mut TheType调用from

希望代码能更好地解释它:

enum Component {
    Position(Point),
    //other stuff
}
struct Point {
    x: i32,
    y: i32,
}
impl<'a> std::convert::From<&'a mut Component> for &'a mut Point {
    fn from(comp: &'a mut Component) -> &mut Point {
        // If let or match for Components that can contain Points
        if let &mut Component::Position(ref mut point) = comp {
            point
        } else { panic!("Cannot make a Point out of this component!"); }
    }
}
// Some function somewhere where I know for a fact that the component passed can contain a Point. And I need to modify the contained Point. I could do if let or match here, but that would easily bloat my code since there's a few other Components I want to implement similar Froms and several functions like this one. 
fn foo(..., component: &mut Component) {
    // Error: Tries to do a reflexive From, expecting a Point, not a Component
    // Meaning it is trying to make a regular point, and then grab a mutable ref out of it, right?
    let component = &mut Point::from(component)
    // I try to do this, but seems like this is not a thing.
    let component = (&mut Point)::from(component) // Error: unexpected ':'
    ...
}

我在这里想做的事情可能吗?上面的impl From编译得很好,只是逃脱了我的召唤。

一种方法是指定component的类型,如下所示:

let component: &mut Point = From::from(component);

正如西蒙·怀特黑德(Simon Whitehead(指出的那样,更惯用的方法是使用相应的函数into()

let component: &mut Point = component.into();

正确的语法是:

let component = <&mut Point>::from(component);

它本质上是没有前导::的"涡轮鱼"语法。

最新更新