0

I'm getting back a String from a function reading a file and now I want to split the returned string content, but I'm not able to return the Vec<&str> of generated Strings to the caller.

It is obvious to me that a borrow occurs with string.split("\n") and therefore a return is not possible because of references, but the compiler error is not guiding me to a solution.

What am I not able to grasp?

Following Split string only once in Rust and subsequent links/posts didn't help me so far.

use std::str::Split;

fn main() {
    let value = process();

    println!("Ergebnis: {:?}", value);
}

fn process<'a>() -> Vec<&'a str> {
    let testballon = Ok("testzztestztest");

    let string: String = match testballon {
        Ok(content) => content.to_string(),
        Err(err) => err,
    };

    let string = if string.contains("zz") {
        string.replace("zz", "n")
    } else {
        string.replace("z", "n")
    };

    let lines: Split<&str> = string.split("\n");

    let v: Vec<&str> = lines.collect();

    v
}
error[E0515]: cannot return value referencing local variable `string`
  --> src/main.rs:27:5
   |
23 |     let lines: Split<&str> = string.split("\n");
   |                              ------ `string` is borrowed here
...
27 |     v
   |     ^ returns a value referencing data owned by the current function
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
seleukos
  • 15
  • 4
  • 1
    It works if you adjust `process` so that it returns a `Vec`. – E_net4 May 12 '21 at 16:26
  • [The duplicate applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1aa380e607e3f3a9beef2d9e9409856b) – Shepmaster May 12 '21 at 16:38

0 Answers0