1

煮詰めた問題は次のようになります。

use std::marker::PhantomData;

struct WorldState<'a> {
    state: &'a f64,
}

trait CalculateWorldState<T> {
    fn state_value(&mut self, input: &T) -> f64;
}


trait LearningAlgorithm<T> {
    fn print_learning_information(&self, &T);
}

struct EvolutionaryAlgorithm<F, T>
where
    F: CalculateWorldState<T>,
{
    //I need this since I only use T as a method parameter, I do not save it anywhere
    //T are different ways to represent the current worldstate and are
    //short-lived (new ones generated every frame)
    _p_: PhantomData<T>,
    //I don't actually need this one in the real example since I have
    //an instatiated version of type CalculateWorldState saved in the
    //struct but I use phantomdata for simplicity of the example
    _p: PhantomData<F>,
}

impl<F, T> LearningAlgorithm<T> for EvolutionaryAlgorithm<F, T>
where
    F: CalculateWorldState<T>,
{
    fn print_learning_information(&self, input: &T) {
        println!("My learning goes splendid!");
        //do something with &T by calling the object of type
        //CalculateWorldState which we have saved somewhere, but do
        //not save the &T reference anywhere, just look at it
    }
}

struct WorldIsInGoodState {}

impl<'a> CalculateWorldState<WorldState<'a>> for WorldIsInGoodState {
    fn state_value(&mut self, input: &WorldState) -> f64 {
        100.
    }
}

fn main() {
    let mut a: Box<LearningAlgorithm<WorldState>> =
        Box::new(EvolutionaryAlgorithm::<WorldIsInGoodState, WorldState> {
            _p: PhantomData,
            _p_: PhantomData,
        });
    {
        let state = WorldState { state: &5. };
        a.print_learning_information(&state);
    }
}

遊び場

上記のコードはコンパイルに失敗します:

error[E0597]: borrowed value does not live long enough
  --> src/main.rs:59:5
   |
57 |         let state = WorldState { state: &5. };
   |                                          -- temporary value created here
58 |         a.print_learning_information(&state);
59 |     }
   |     ^ temporary value dropped here while still borrowed
60 | }
   | - temporary value needs to live until here

WorldState<'a>は非常に寿命の短いデータ型 (フレームごとに 1 つ)LearningAlgorithmですが、 は非常に寿命の長いデータ型 (複数のゲーム) です。しかし、私がこのことを実装した方法では、Rust は、WorldState私が渡したすべてprint_learning_informationLearningAlgorithm.

私は何を間違えましたか?これは他にどのように処理できますか?

私がしたくないいくつかのこと:

  • WorldState通常の状態が含まれています (実際には、ベクトルではなくいくつかのベクトルが含まれており、各プレイヤーに独自の世界観を渡すときにf64それらを構造体にコピーしたくないため)WorldState
  • このプロジェクトを終了して、新しいプロジェクトを開始するだけです (ご存知のように、ある程度の時間を費やした後は、すべての作業を放棄したくはありません)。
4

1 に答える 1