kreo
kreo

Reputation: 2841

Why does a &[T] argument also accept &Vec<T>?

I am working through the Rust book, namely the minigrep project. There I came across the following snippet:

fn main() {
    let args: Vec<String> = env::args().collect();

    let (query, filename) = parse_config(&args);

    // --snip--
}

fn parse_config(args: &[String]) -> (&str, &str) {
    let query = &args[1];
    let filename = &args[2];

    (query, filename)
}

The confusing piece for me is args: &[String]. If I replace it with args: &Vec<String>, it also works. My guess is that &[String] is a more general type annotation that matches not only &Vec<String>, but also some other types. Is that correct? If so, what other types are matched by [T]?

Upvotes: 5

Views: 1430

Answers (1)

ljedrz
ljedrz

Reputation: 22283

Generally speaking, [T] is a contiguous sequence and &[T] is a slice.

The reason why the compiler allows &[String] instead of &Vec<String> is that Vec<T> dereferences to [T]. This is called Deref coercion. It can be said that the former notation (in function parameters) is more general; it is also the preferred one. Further details about automatic dereferencing rules can be found in this question.

Upvotes: 7

Related Questions