返回包含可变值的结构 [英] Returning a struct containing mutable values

查看:44
本文介绍了返回包含可变值的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我试图在其中返回结构 Foo 和字段 values 的一组默认值.这些值可能会在以后更改.但是编译器抱怨:

错误:`initial` 寿命不够长

这是如何实现的?有其他选择吗?

struct Foo <'a>{值:&'a mut Vec<i32>,}impl <'a>Foo <'a>{fn new() ->Foo <'a>{让初始 = vec![1, 2];Foo { 值:&mut 初始 }}}让 my_foo = Foo::new();my_foo.values.push(3);

解决方案

这里有两个问题.

第一个是您不需要使用 &mut 来使结构字段可变.可变性在 Rust 中继承.也就是说,如果你有一个 Foo 存储在一个可变变量(let mut f: Foo)中,它的字段是可变的;如果它在一个不可变变量中(let f: Foo),它的字段是不可变的.解决方案是使用:

struct Foo {值:Vec i32 ,}

并按值返回一个 Foo.

第二个问题(也是实际编译错误的来源)是您试图将借用返回到您在函数中创建的内容.这是不可能的.不,没有办法绕过它;你不能以某种方式延长 initial 的生命周期,返回 initial 以及借用将不起作用.真的.这是 Rust 专门设计绝对禁止的事情之一.

如果你想从一个函数中传出某些东西,必须满足以下两点之一:

  1. 它被存储在函数之外的某个地方,它将比当前调用更有效(例如,你被给予一个借用作为参数;返回不算),或者>

  2. 您要归还所有权,而不仅仅是借来的参考资料.

更正后的 Foo 有效,因为它拥有Vec.

I have the following code, where I'm trying to return the struct Foo with a set of default values for the field values. These values may be changed later. But the compiler complains:

error: `initial` does not live long enough

How this could be achieved? Any alternatives?

struct Foo <'a> {
    values: &'a mut Vec<i32>,
}

impl <'a> Foo <'a> {
    fn new() -> Foo <'a> {
        let initial = vec![1, 2];

        Foo { values: &mut initial }
    }
}

let my_foo = Foo::new();

my_foo.values.push(3);

解决方案

There are two problems here.

The first is that you don't need to use &mut to make a structure field mutable. Mutability is inherited in Rust. That is, if you have a Foo stored in a mutable variable (let mut f: Foo), its fields are mutable; if it's in an immutable variable (let f: Foo), its fields are immutable. The solution is to just use:

struct Foo {
    values: Vec<i32>,
}

and return a Foo by value.

The second problem (and the source of the actual compilation error) is that you're trying to return a borrow to something you created in the function. This is impossible. No, there is no way around it; you can't somehow extend the lifetime of initial, returning initial as well as the borrow won't work. Really. This is one of the things Rust was specifically designed to absolutely forbid.

If you want to transfer something out of a function, one of two things must be true:

  1. It is being stored somewhere outside the function that will outlive the current call (as in, you were given a borrow as an argument; returning doesn't count), or

  2. You are returning ownership, not just a borrowed reference.

The corrected Foo works because it owns the Vec<i32>.

这篇关于返回包含可变值的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆