impl convert::From 用于(可变)引用

impl convert::From for (mutable) reference

我正在尝试为我想作为可变引用获取的类型实现 From,因此我将其实现为 &mut TheType,但是我该如何正确调用 [=14] =]?我执行的尝试失败了,因为它尝试进行反射(TheType 来自 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 pointed out, the more idiomatic way to do this would be to use the corresponding function into():

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

正确的语法是:

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

它本质上是没有前导 :: 的 "turbofish" 语法。