为什么我的变量寿命不足? [英] Why does my variable not live long enough?

查看:64
本文介绍了为什么我的变量寿命不足?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段简单的代码,应该可以将文件按行读入向量

I have a simple piece of code that is supposed to read a file into a vector by lines

use std::io::{self, Read};
use std::fs::File;

fn file_to_vec(filename: &str) -> Result<Vec<&str>, io::Error> {
    let mut file = try!(File::open(filename));
    let mut string = String::new();
    try!(file.read_to_string(&mut string));
    string.replace("\r", "");

    let data: Vec<&str> = string.split('\n').collect();

    Ok(data)
}

fn main() {}

我遇到以下错误:

error[E0597]: `string` does not live long enough
  --> src/main.rs:10:27
   |
10 |     let data: Vec<&str> = string.split('\n').collect();
   |                           ^^^^^^ does not live long enough
...
13 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 4:1...
  --> src/main.rs:4:1
   |
4  | / fn file_to_vec(filename: &str) -> Result<Vec<&str>, io::Error> {
5  | |     let mut file = try!(File::open(filename));
6  | |     let mut string = String::new();
7  | |     try!(file.read_to_string(&mut string));
...  |
12 | |     Ok(data)
13 | | }
   | |_^

为什么我不断收到此错误?我该如何解决?我想这与split方法有关.

Why do I keep getting this error? How do I fix this? I imagine that it has something to do with the split method.

我可以返回字符串,然后在主函数中将其拆分为Vec,但是我真的想返回向量.

I could return the string and then split it into a Vec in the main function, but I really want to return a vector.

推荐答案

问题是string是在您的函数中创建的,并且在函数返回时将被销毁.您要返回的向量包含string的切片,但这些切片在您的函数之外将无效.

The problem is that string is created in your function and will be destroyed when the function returns. The vector you want to return contains slices of string, but those will not be valid outside of your function.

如果您不十分担心性能,则可以从函数中返回Vec<String>.您只需将类型返回为Result<Vec<String>, io::Error>并更改行

If you're not terribly worried about performance, you can return a Vec<String> from your function. You just have to return type to Result<Vec<String>, io::Error> and change the line

let data: Vec<&str> = string.split('\n').collect();

let data: Vec<String> = string.split('\n').map(String::from).collect();

这篇关于为什么我的变量寿命不足?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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