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

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

问题描述

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

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("
", "");

    let data: Vec<&str> = string.split('
').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('
').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.您只需要将类型返回到 Result, 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('
').collect();

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

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

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