0

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
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Shodai Thox
  • 117
  • 5
  • Also [Return local String as a slice (&str)](https://stackoverflow.com/questions/29428227/return-local-string-as-a-slice-str). – Chayim Friedman Jun 23 '22 at 10:23
  • Return `Vec` instead, and do `string.split("\n").map(|v| v.to_owned()).collect()`. Note that the local `my_vec` variable is redundant, as is the initialization, since the empty `Vec` you create is just clobbered with assignment later and then immediately returned. – cdhowie Jun 23 '22 at 10:36
  • @cdhowie Thanks as well, your solution works, but can you explain me the .map() part, please ? – Shodai Thox Jun 23 '22 at 10:43
  • @ShodaiThox [`Iterator::map()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map). – Chayim Friedman Jun 23 '22 at 10:43
  • @ChayimFriedman It makes sense now, so basically I have a borrowed string but it needs to be owned so it can be returned by the function right? if yes, the value of "String" that stores the content of the file is cleared after we terminate "file" function ? – Shodai Thox Jun 23 '22 at 11:00
  • Yes. This is what happens. – Chayim Friedman Jun 23 '22 at 11:06

0 Answers0