如何构造和返回两个值,其中一个引用另一个 [英] How do I construct and return two values, one of which references the other

查看:51
本文介绍了如何构造和返回两个值,其中一个引用另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说一个 B 包含对 A 的引用:

struct A;

struct B<'t> {
    a_ref: &'t A,
}

我的目标是编写一个简单的函数 f ,使以下两个等价(尽管其中一个可以使用堆).

My goal is to write a simple function f that makes the following two equivalent (though one may use the heap).

let (a, b) = f();

let a = A { };
let b = B { a_ref: &a };

我怎么写 f ?这是一个尝试:

How would I write f? Here's an attempt:

fn f<'t>() -> (A, B<'t>) {
    let a = A { };
    let b = B { a_ref: &a };
    (a, b)
}

但是它无法编译出两个错误,据我所知,但不确定如何避免:

But it fails to compile with two errors, which I understand but am not sure how to avoid:

错误[E0515]:无法返回引用局部变量`a`

错误[E0505]:因为它是借来的,所以无法移出`a`

我看过

I have seen Why can't I store a value and a reference to that value in the same struct?. Above, I wrote two lines of code that create an A and a B. My question is not why my attempt to abstract those two lines fails. My question is how to abstract (something like) those two lines.

是的,我尝试将值和对该值的引用存储在结构中,但是无论如何,这不是目标.我知道那是行不通的.那不是我要完成的.我的目标是无关紧要的,无论如何都可能实现.例如,返回闭包或使用宏即可.

Yes, my attempt tries to store a value and a reference to that value in a struct, but whatever, that is not the goal. I know that does not and cannot work. That is not what I'm trying to accomplish. My goal is something unrelated and which may be possible regardless. For example, returning a closure or using a macro could work.

推荐答案

因此,这里的问题是 f 向调用者提供了 a 的所有权:

So the problem here is that f is giving out ownership of a to its caller:

  1. a 是在 f 中创建的. a 属于 f .
  2. f 返回 a ,并将所有权转移给其调用者.
  3. 现在,
  4. a 已从 f 移动 到呼叫者.
  1. a is created inside f. a belongs to f.
  2. f returns a, transferring ownership to its caller.
  3. a is now moved from f to the caller.

移动的问题是它们有权在内存中移动变量.这将使对该变量的所有引用无效,因此,每当移动变量时都不允许引用该变量.

The problem with moves is that they have the right to move the variable in memory. This would invalidate all references to that variable, and therefore no references are allowed to a variable whenever it is moved.

您可以做的是让 f 收到对 a 的引用,并返回一个对 a :示例.

What you could do is have f receive a reference to a and return a new B with a reference to a: example.

这篇关于如何构造和返回两个值,其中一个引用另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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