如何定义返回引用内部字段的结构的特征

问题描述

我正在尝试为算法定义一个特征,该特征在算法的每个步骤后返回一个引用多个内部字段的结构。然后调用代码可以选择序列化状态信息或显示它。我想将它作为引用返回,这样如果调用代码不使用它,就不会影响性能(内部状态可能非常大)。

下面是我认为我想要的,但我希望它是算法特征的通用性,然后为 FooAlgorithm 或其他实现算法特征。

use serde::{Deserialize,Serialize}; // 1.0.125

struct FooStateRef<'a> {
    field_0: &'a usize,field_1: &'a usize,}

impl<'a> Clone for FooStateRef<'a> {
    fn clone(&self) -> Self {
        FooStateRef {
            field_0: self.field_0,field_1: self.field_1,}
    }
}

impl<'a> copy for FooStateRef<'a> {}

#[derive(Debug,Serialize,Deserialize)]
struct FooState {
    field_0: usize,field_1: usize,}

struct FooAlgorithm {
    field_0: usize,// Don't want to clone unless the calling code wants to serialize
    field_1: usize,// Don't want to clone unless the calling code wants to serialize
    field_2: usize,// No need to serialize
}

impl<'a> From<FooStateRef<'a>> for FooState {
    fn from(state: FooStateRef) -> FooState {
        FooState {
            field_0: state.field_0.clone(),field_1: state.field_1.clone(),}
    }
}

impl FooAlgorithm {
    fn step(&mut self) -> Option<FooStateRef> {
        self.field_1 += self.field_0;
        self.field_2 += self.field_1;
        self.field_0 += self.field_2;

        if self.field_2 > 100 {
            Some(FooStateRef {
                field_0: &self.field_0,field_1: &self.field_1,})
        } else {
            None
        }
    }
}

fn main() {
    let mut algo = FooAlgorithm {
        field_0: 1,field_1: 1,field_2: 1,};

    let mut count = 0;
    loop {
        match algo.step() {
            Some(state_ref) => {
                if count % 10 == 0 {
                    // Save state to file
                }
            }
            None => break,}
        count += 1;
    }
}

我尝试制作算法特征的尝试在这里https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5a36c6eb121f0724284bf7d5ec5a8cad

我遇到的问题是生命周期。如何在算法特征定义中编写函数签名,以便在为 FooAlgorithm 实现 Algorithm 时可以返回 FooStateRef,但在为 Baralgorithm 实现 Algorithm 时也让我返回 BarStateRef?

我研究过的另一件事是关联类型,但据我所知,我需要通用关联特征将 type AlgoStateRef<'a>: StateRef<'a>; 之类的内容添加到算法特征定义中。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)