Why does my variable not live long enough?

后端 未结 1 575
耶瑟儿~
耶瑟儿~ 2020-11-28 00:20

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:          


        
相关标签:
1条回答
  • 2020-11-28 00:43

    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.

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

    to

    let data: Vec<String> = string.split('\n').map(String::from).collect();
    
    0 讨论(0)
提交回复
热议问题