I want to open a file, store its content in a String
and then split the data between each end line "\n", then store the result into a Vec<&str>
. Just so you know, I'm trying to do it on a separated functions on different files.
Here's the code
//this is the code on the file_handing.rs
use std::fs::File;
use std::io::prelude::*;
pub fn file() -> Vec<&'static str>{
let mut file = File::open("testfile").expect("Can't read file.");
let mut string = String::new();
let mut my_vec: Vec<&str> = Vec::new();
file.read_to_string(&mut string).expect("Can't read file.");
my_vec = string.split("\n").collect();
return my_vec
}
//this is the code on the main.rs
mod file_handing;
fn main() {
let l: Vec<&str> = file_handing::file();
println!("{:?}", l);
}
And here's the error:
error[E0515]: cannot return value referencing local variable `string`
--> src\test.rs:13:12
|
10 | my_vec = string.split("\n").collect();
| ------------------ `string` is borrowed here
...
13 | return my_vec
| ^^^^^^ returns a value referencing data owned by the current function