2017-02-09 37 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」語法。