0

I am doing rustlings exercises. Here are my answer for iterator2.rs:

// Step 1.
// Complete the `capitalize_first` function.
// "hello" -> "Hello"
pub fn capitalize_first(input: &str) -> String {
    let mut c = input.chars();
    match c.next() {
        None => String::new(),
        Some(first) => first.to_uppercase().to_string() + c.as_str()
    }
}

// Step 2.
// Apply the `capitalize_first` function to a slice of string slices.
// Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"]
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
    words.iter().map(|w| {capitalize_first(w)}).collect()
}

The capitalize_first() function requires a &str argument, but the type of parameter w in the closure of map() is &&str (inferred by Clion). The compiler doesn't complain anything and I can pass the exercise. So what's going on behind the scene?

type inferred by Clion

StrikeW
  • 501
  • 1
  • 4
  • 11
  • 1
    Rust performs automatic [deref coercion](https://doc.rust-lang.org/book/ch15-02-deref.html#implicit-deref-coercions-with-functions-and-methods) on arguments. – eggyal Apr 28 '22 at 08:30
  • Another relevant question: https://stackoverflow.com/questions/53341819/what-is-the-relation-between-auto-dereferencing-and-deref-coercion – Jmb Apr 28 '22 at 08:54

0 Answers0