0

When I do exercise in rustlings, I found that exercise:

pub fn capitalize_words_string(words: &[&str]) -> String {}

i try to change function to

pub fn capitalize_words_string(words: &Vec<&str>) -> String {}

It also works properly, So my question is what is different between &[&str] with &Vec<&str> in rust? Thanks!

  • Does this answer your question: https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-to-a-string-string-vec-vec-o – user4815162342 Feb 20 '22 at 16:03

1 Answers1

0

Let's substitute the inner &str with T. Then &[T] is a slice of T and &Vec<T> is a reference to a vector of T.

When a function is defined to accept a &[T], you can also pass a &Vec<T>. Another very common case is to declare a parameter as &str, as that allows you to directly pass, for example &String. This is known as Deref coercion.

cameron1024
  • 9,083
  • 2
  • 16
  • 36
at54321
  • 8,726
  • 26
  • 46
  • Thanks, which one is best for define it as parameter in function? – minikiller Feb 20 '22 at 15:04
  • Usually `&[T]` is better, as it is more generic. If you have a `&Vec` parameter, you can only pass a `&Vec` value. If you are familiar with languages like Java or .NET, it's somewhat similar to using an interface, as opposed to a concrete class. – at54321 Feb 20 '22 at 15:06
  • 1
    It's also worth mentioning that pretty much all of the non-mutating methods on `Vec` are [actually defined on `[T]`](https://doc.rust-lang.org/std/vec/struct.Vec.html#deref-methods-%5BT%5D) (you can call them on `Vec` because method calls are another place where derefs implicitly happen). Therefore, taking a `&[T]` instead of a `&Vec` is pretty much always preferable - it makes the function more flexible without losing any functionality. – Joe Clay Feb 20 '22 at 15:07
  • 1
    Good point, @JoeClay – at54321 Feb 20 '22 at 15:09
  • I understand what your said. when we use slice, it can accept slice also can accept reference just like &str and &String. Thanks. – minikiller Feb 20 '22 at 15:13