impl convert :: From for(mutable)reference

GGa*_*zzi 2 traits rust

我正在尝试实现From一个我想要作为一个可变参考的类型,所以我把它推到一个&mut TheType,但那我该怎么称呼from?我尝试执行的尝试失败,因为它尝试做反射(TheType from TheType)或不能(或不知道如何)from从类型调用&mut TheType.

代码将更好地解释它:

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 ':'

    ...
}
Run Code Online (Sandbox Code Playgroud)

我在这里想做的可能吗?在impl From上述编译就好了,是的,它只是调用逃脱我.

Wes*_*ser 5

一种方法是指定component类似的类型:

let component: &mut Point = From::from(component);
Run Code Online (Sandbox Code Playgroud)

正如西蒙怀特黑德指出的那样,更为惯用的方法是使用相应的功能into():

let component: &mut Point = component.into();
Run Code Online (Sandbox Code Playgroud)

  • 另外,因为stdlib包含许多变体`impl <T,U>进入<U>代表T,其中U:From <T>`你也可以在实现`From`后执行此操作:`let component:&mut Point = component.入();` (3认同)