Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a vector and return a vector of strings?

Tags:

rust

I'm trying to figure out what I need to do to pass a vector and return a vector of strings in order to solve the anagram exercise on exercism.io.

Here is the test that I'm trying to pass:

fn test_no_matches() {
    let inputs = ["hello", "world", "zombies", "pants"];
    let outputs: Vec<&str> = vec![];
    assert_eq!(anagrams_for("diaper", &inputs), outputs);
}

and here is what I have written so far:

pub fn anagrams_for<'a>(word: &str, inp: Vec<&'a str>) -> Vec<&'a str> {
    let mut out: Vec<&str> = vec![];
    let ref poss = *inp[1];
    out.push(poss);
    out
}

But the test fails to compile at &inputs, giving me this error:

error[E0308]: mismatched types
 --> src/lib.rs:4:39
  |
4 |     assert_eq!(anagrams_for("diaper", &inputs), outputs);
  |                                       ^^^^^^^
  |                                       |
  |                                       expected struct `std::vec::Vec`, found `&[&str; 4]`
  |                                       help: try using a conversion method: `(&inputs).to_vec()`
  |
  = note: expected struct `std::vec::Vec<&str>`
          found reference `&[&str; 4]`

I've read about references, borrowing, and lifetimes. I can honestly say that I am a bit confused about passing references around. I thought about the return vector as just a Vec<String> but I think there was an issue about the input vectors reference to a str that was causing the problems.

If anyone could push me in a better direction that would be appreciated as I don't want to Kirk the test.

like image 804
macshaggy Avatar asked Dec 18 '22 16:12

macshaggy


1 Answers

Just change your function signature from

pub fn anagrams_for<'a>(word: &str, inp: Vec<&'a str>) -> Vec<&'a str>

to

pub fn anagrams_for<'a>(word: &str, inp: &[&'a str]) -> Vec<&'a str>

&[T] can accept both v: Vec<T> and v: [T; n] as arguments by using &v.

like image 138
WiSaGaN Avatar answered Jan 19 '23 08:01

WiSaGaN