2017-07-02 13 views
2

私は、Java/JavaScriptのバックグラウンドから生まれたRustを始めたばかりです。私は生涯の理解に何かが欠けているので、私に負担をかけてください。生涯には何か不足していますか?

fn main() { 
    struct Appearance<'a> { 
     identity:  &'a u64, 
     role:   &'a str 
    }; 
    impl<'a> PartialEq for Appearance<'a> { 
     fn eq(&self, other: &Appearance) -> bool { 
      self.identity == other.identity && self.role == other.role 
     } 
    }; 
    let thing = 42u64; 
    let hair_color = "hair color"; 
    let appearance = Appearance { 
     identity: &thing, 
     role: &hair_color 
    }; 
    let another_thing = 43u64;  
    let other_appearance = Appearance { 
     identity: &another_thing, 
     role: &hair_color 
    }; 
    println!("{}", appearance == other_appearance); 
} 

コンパイラはother_appearanceに達し、これはanother_thingは十分に長く住んでいないことを私に言って、私にコンパイルエラーを与えています。しかし、私がother_appearanceの作成を省いた場合、プログラムはコンパイルされて正常に動作します。なぜこのエラーが発生するのですか?

答えて

5

PartialEq traitには、右側のタイプを指定するタイプパラメータがあります。あなたがそれを指定しなかったので、デフォルトは左辺と同じ型になります。これは、両面が同じ寿命を有すると仮定されることを意味する。 another_thingappearanceの前に削除されているためにエラーが発生しますが、other_appearanceanother_thingへの参照を保持します)の有効期間はappearanceであると見なされます。

あなたは右側に異なる寿命を使用することで、この問題を解決することができます

impl<'a, 'b> PartialEq<Appearance<'b>> for Appearance<'a> { 
    fn eq(&self, other: &Appearance<'b>) -> bool { 
     self.identity == other.identity && self.role == other.role 
    } 
}; 
+0

これは実際には '#[derive(PartialEq)]によって作成されたインスタンスがOPと同じ問題を抱えているので興味深いです。 –

+0

これとは逆に、値が宣言されている順序と逆の順序でドロップされるため、順序を入れ替えることで修正することもできます。つまり、 'appearance == other_appearance'の代わりに' other_appearance == appearance'を使います。はい、錆はいくつかの疣贅を持っています... –

+0

ありがとう!私はあなたが言ったことを概念的に理解していても、構文にとどまる必要があります:) –

1

これは、==シンタックスシュガーと組み合わせると、生涯の推論/分散の問題と思われます.-比較をPartialEq::eq(&appearance, &other_appearance)に置き換えると動作することに注意してください。これが既知のバグかどうかはわかりません。

+0

奇妙な。これはバグでなければなりません。代わりに、あなたが '[PartialEq]を派生させたときに' 'OPと同じ動作をするので、これは特に驚くべきことです。 –

関連する問題