繁体   English   中英

如何获得结构(受生命周期约束)字段的可变引用?

[英]How to get mutable reference of struct(constrained with lifetime) field?

坦率地说,我不知道标题是否完美地描述了我的问题。
我自己也不知道是什么问题。
无论如何,我都会出错。

我的代码是

// main.rs
#[derive(Debug)]
struct A<'a> {
    f1: B<'a>,
    f2: i32,
}

#[derive(Debug)]
struct B<'a> {
    f1: Vec<&'a str>,
}

impl<'a> A<'a> {
    fn new() -> Self {
        Self {
            f1: B::new(),
            f2: 0,
        }
    }

    fn set_f1(&mut self, b: B<'a>) {
        self.f1 = b;
    }

    fn get_f1(&mut self) -> &mut B {
        &mut self.f1
    }

    fn execute(&mut self) {
        self.get_f1().set_f1()
    }
}

impl<'a> B<'a> {
    fn new() -> Self {
        Self {
            f1: vec!["string literal"],
        }
    }

    fn set_f1(&mut self) {
        self.f1 = vec!["changed"]
    }
}

fn main() {
    let mut a = A::new();
    let mut b = B::new();
    let mut b2 = B::new();
    a.set_f1(b); // for testing
    a.set_f1(b2); // for testing

    a.execute();

    // a.get_f1().set_f1(); this is working here but not in method execute. Why?
}

这是完美的示例重复(更简单的版本,忽略所有其他字段和方法)代码。
除了使用字符串文字&str而不是String之外,我别无选择,因为它更容易进行模式匹配。

所以,我介绍了生命周期。 我不知道它是否正确或者是最佳实践之一。

我需要A的字段f1是可变的,所以我可以更改Bf1字段。
如何实施?

我尝试了一些方法,这里是代码的链接。 https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=338c30cb225a3a48f71c250affea8623

    fn get_f1(&mut self) -> &mut B<'a> {
      &mut self.f1
    }

您应该明确定义 get_f1 的返回值的提升时间

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM