[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();

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.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.