1

There's an object that only accepts &[&str] as input, but I need to generate this list dynamically. I tried many ways but I always get errors.

My code:

use std::fs;

fn example() {
    let paths = fs::read_dir("./").unwrap();
    let mut input_files = Vec::<&str>::new();
    for path in paths {
        let x = ["../", path.unwrap().path().to_str().unwrap()]
            .concat()
            .as_str();
        input_files.push(x);
    }
}

Error:

error[E0716]: temporary value dropped while borrowed
  --> src/lib.rs:8:17
   |
8  |           let x = ["../", path.unwrap().path().to_str().unwrap()]
   |  _________________^
9  | |             .concat()
   | |_____________________^ creates a temporary which is freed while still in use
10 |               .as_str();
   |                        - temporary value is freed at the end of this statement
11 |           input_files.push(x);
   |                            - borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

I think the error is because concat creates a temporary, but why? Why can it not return a string and how should I fix this?

I can't use String.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • tl;dr the duplicate: [use `String`, not `&str`](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=977b0530207f051ce8a35681e35d71a0) – trent Sep 28 '20 at 22:38
  • Also consider [Temporary value dropped while borrowed, but I don't want to do a let](/q/59193616/3650362) and [How do I add references to a container when the borrowed values are created after the container?](/q/44987555/3650362) – trent Sep 28 '20 at 22:41
  • @trentcl but I need to pass a slice of `&str` to an object. How can I do that if I use `Vec`? – Guerlando OCs Sep 28 '20 at 22:48
  • It would depend on the context. If you really need to, you can make a second `Vec` to hold references to the `str`s, but they still have to be owned somewhere before you can borrow them. Some APIs that take slices of strings (including `concat` itself) are designed to accept `&[S: AsRef]` instead of just `&[&str]` so you can avoid making a new `Vec`. – trent Sep 28 '20 at 23:10
  • 1
    [This answer shows how to allocate a `Vec<&str>` to satisfy an API that demands `&[&str]`](https://stackoverflow.com/a/41179800/3650362). – trent Sep 28 '20 at 23:22
  • 1
    [The duplicate applied to your code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b7fdc51e95772a833af9c5aeeb63f9db). – Shepmaster Sep 29 '20 at 00:07

0 Answers0