【问题标题】:Conditionally update argument to function in Rust [duplicate]有条件地更新 Rust 中的函数参数 [重复]
【发布时间】:2021-04-17 20:19:29
【问题描述】:

我正在尝试有条件地更新函数的参数:

struct A {
    foo: i32,
    bar: i32,
}

impl A {
    fn foobar<'a>(&'a self) {
        let a;
        if true { // something more complex obviously
            let x = A {
                foo: self.foo,
                bar: self.bar,
            };
            a = &x;
        } else {
            a = self;
        }
        
        println!("{} {}", a.foo, a.bar);
    }
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=27fcba42d135da6282bd000fd8e3db5d

这里,函数foobar 接收&amp;A 类型的参数。根据某些情况,我想将此参数替换为 &amp;A 类型的另一个值。

我明白为什么上面的代码会导致错误'x' does not live long enough。我的问题是是否有一种模式可以有条件地更新参数a 的值而不要求它是可变的?有没有办法强制延长x 的生命周期?

【问题讨论】:

  • 真的只是在两个分支中调用你的函数。

标签: rust


【解决方案1】:

在您的if 条件中,您向a 提供对x 的引用,该引用将在之后被销毁。然后a 将持有对已销毁对象的引用。

您可以通过在条件前声明x 变量来修复它:

struct A {
    foo: i32,
    bar: i32,
}

impl A {
    fn foobar<'a>(&'a self) {
        let a;
        let x;
        if true { // something more complex obviously
            x = A {
                foo: self.foo,
                bar: self.bar,
            };
            a = &x;
        } else {
            a = self;
        }

        println!("{} {}", a.foo, a.bar);
    }
}

您还可以通过删除生命周期并使用模式 let a = if ... {} else {}; 来简化代码:

    fn foobar(&self) {
        let x;
        let a = if true { // something more complex obviously
            x = A {
                foo: self.foo,
                bar: self.bar,
            };
            &x
        } else {
            self
        };

        println!("{} {}", a.foo, a.bar);
    }

【讨论】:

  • 请注意,这会增加运行时开销,在我看来是丑陋的代码。
猜你喜欢
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2020-06-26
  • 2012-12-09
  • 2021-08-28
  • 2017-07-19
  • 1970-01-01
相关资源
最近更新 更多