1

I'm trying to add a couple entries to a vec but I keep getting mismatching types:

pub fn create_lib_file(name: &str, targets: Vec<&str>) -> String {
    let mut my_vec = vec![
        "[lib]",
        "",
        "",
        "[files]",
        "",
        "",
        "[general]",
        "",
    ];

    // The targets are just strings passed from the CLI command.
    for t in targets {
        match t {
            "one" => {
                let file_name = format!("user/test/{}.dll", name);
                let slice = &[file_name];
                my_vec.splice(2..2, slice.iter().cloned());
            }
        }
    }

    return my_vec.join("\n");
}

This gives me an error:

error[E0271]: type mismatch resolving `<std::slice::Iter<'_, std::string::String> as std::iter::Iterator>::Item == &&str`
  --> src/lib.rs:19:24
   |
19 |                 my_vec.splice(2..2, slice.iter().cloned());
   |                        ^^^^^^ expected struct `std::string::String`, found `&str`
   |
   = note: expected reference `&std::string::String`
              found reference `&&str`
   = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Cloned<std::slice::Iter<'_, std::string::String>>`

I assume that this has to do with the file_name so I tried using to_owned() and to_string() but nothing I've tried so far to convert the file_name to String has worked.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mr.Smithyyy
  • 2,157
  • 12
  • 49
  • 95
  • 1
    You probably wanted the opposite conversion `String` to `&str`, although other problems may emerge from there. Consider whether owning the strings would be more appropriate, or perhaps even going for a hybrid approach with `Cow`. – E_net4 Apr 27 '20 at 13:30
  • 1
    In Rust, string literals are of type `&'static str`, so `my_vec` has the type `Vec<&'static str>`. `format` generates a `String`, you can't put a `String` inside a `Vec<&str>`. This means you may want `my_vec` to be a `Vec`. Either that, or first generate the various values you want to put into the vec, then create a literal slice in order to `join()` it. – Masklinn Apr 27 '20 at 13:49
  • 1
    The duplicates [applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7d1f8914b98371d7f130944efd5acbd5), using a memory-efficient method (but not necessarily the shortest). – Shepmaster Apr 27 '20 at 13:52
  • 1
    @Shepmaster works great thank you! Just when I think I'm starting to grasp the basics I get hit with something like this and I feel like I know nothing. – Mr.Smithyyy Apr 27 '20 at 14:07
  • 2
    @Mr.Smithyyy that's the process of learning — sometimes frustrating, sometimes smooth, but in the end we learn it one way or the other! – Shepmaster Apr 27 '20 at 14:09

0 Answers0