[Solved] Beginner: Why is &[String] compatible to &Vec<String>?

Here is a example:

use std::env;


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

fn parse_config(args: &[String]) {
    // to do something
}

The type of args is the reference of Vec<String> while the type of parameter args in parse_config function is the reference of [String].

That’s the magic of Deref. You can click on Deref to get a full explanation, but in this case, it’s kinda simple: Vec<T> implements Deref<Target=[T]>, which means that wherever you need a &[T], you can actually put in a &Vec<T>. For T=String, this is exactly what you’re seeing.

5 Likes