2017-02-09 71 views
2

我试图实现From为我想获取作为可变引用的类型,所以我impl它为&mut TheType,但那么我该如何正确呼叫from?尝试我执行失败,因为它试图做一个类型&mut TheTypefrom反射(TheType从TheType)或不能(或不知道如何)。impl convert ::从for(mutable)reference

代码将更好地希望解释一下:

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编译得很好,只是它的调用而逃脱了我。要做到这一点

回答

5

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

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

由于Simon Whitehead指出的,更地道的方式来做到这一点是使用相应的功能into()

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

此外,因为STDLIB包括向对于T IMPL 的'许多变型,其中U:从'也可以做到这一点实现'From'后:'让成分:&MUT点= component.into();' –

3

正确语法如下:

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

它本质上是没有领先::的“turbofish”语法。