如何将返回值的生命周期设置为我移入其中的变量的生命周期

如何将返回值的生命周期设置为我移入其中的变量的生命周期

本文介绍了如何将返回值的生命周期设置为我移入其中的变量的生命周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自学一些生锈,并写了一些类似的东西:

I am trying to teach myself some rust, and have written something that looks like:

let args:Vec<String> = env::args().collect();
let parsed = parser::sys(args.as_slice());

...

pub fn sys<'a>(args:&'a [String]) -> Parsed<'a> {
  parsed(args)
}

其中 parsed 是一个解析和加载配置的函数.

where parsed is a function that parses and loads configs.

这很好用.现在我试图抽象出显式调用 env::args() 并将其隐藏在对 sys 的调用中,所以我编写了一个新版本的 sys

This works fine. Now I am trying to abstract away explicitly calling env::args() and hide it in the call to sys , so I write a new version of sys

pub fn sys<'a>() -> Parsed<'a> {
  let args:Vec<String> = env::args().collect();
  parsed(args.as_slice())
}

这失败了:

error: `args` does not live long enough
src/test.rs:66      parsed(args.as_slice())

我认为错误是因为编译器无法推断我希望这个新创建的结构的生命周期是我想要将其移入的变量的生命周期.这样对吗?我将如何在此返回值上注释生命周期/修复此问题?

I think the error is because there's no way for compiler to infer that I want the lifetime of this newly created struct to be the lifetime of the variable I want to move this into. Is this correct? How would I annotate the lifetime on this return value/fix this?

推荐答案

实际上,没有.

错误是因为您试图创建对变量 args 的引用,该引用在您从 sys 返回后将不再有效,因为 args> 是一个局部变量,因此在 sys 的末尾被删除.

The error is because you are trying to create references into the variable args which will no longer be valid after you return from sys since args is a local variable and thus is dropped at the end of sys.

如果你想使用引用,你可以为 sys 提供一个 &'a mut Vec(空),填入 sys,并返回对它的引用:

If you wish to use references, you could supply sys with a &'a mut Vec<String> (empty), fill it in sys, and return references to it:

pub fn sys<'a>(args: &'a mut Vec<String>) -> Parsed<'a> {
    *args = env::args().collect();
    parsed(args.as_slice())
}

保证 argssys 调用更有效.这将在结果的生命周期内借用 args.

which guarantees that args outlive the sys call. This will borrow args for the lifetime of the result.

另一个解决方案是取消 'a 并简单地让 Parsed 拥有它的元素而不是引用它们;但是如果没有 Parsed 的定义,我无法建议如何最好地这样做.

Another solution is to do away with 'a and simply have Parsed own its elements rather than have references to them; however without the definition of Parsed I cannot advise how best to do so.

这篇关于如何将返回值的生命周期设置为我移入其中的变量的生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:17