2017-02-09 3 views
2

私は&mut TheTypeのためにそれを含意するため、Fromを変更可能な参照として取得したいタイプに対して実装しようとしていますが、それではどのように正しく呼び出しますかfrom?試してみてください。試してみてください。試してみてください(TheTypeからTheType)。fromから&mut TheTypeを呼び出してはいけません。impl convert :: 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はうまくコンパイルされ、私を逃れるだけの呼び出しです。これを行うには

答えて

5

一つの方法は、このようなcomponentの種類を指定するには、次のようになります。

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

Simon Whiteheadが指摘したように、これを行うにはより多くの慣用的な方法は、対応する機能into()使用することです:

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

、STDLIB UはT用中へのimpl 'の多くのバリエーション含まれているため、:'コンポーネントを聞かせて:から 'あなたも' From'を実施した後、これを行うことができます&mutのポイント= component.intoを(); ' –

3

正しい構文は次のとおりです。

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

本質的に先導文字なしの「ターボフィッシュ」構文::です。また

関連する問題