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