2

I have a function that takes in a reference to a Vec and applies a filter on it. But this piece of code works with upto three deference operators (*) applied to the closure's parameter. What is the logic behind this in Rust?

fn filter(v: &Vec<String>) {
    // works
    let filt1 = v.iter().filter(|x: &&String| { x.contains("t") });

    // works
    let filt2 = v.iter().filter(|x: &&String| { (*x).contains("t") });

    // works
    let filt3 = v.iter().filter(|x: &&String| { (**x).contains("t") });

    // works
    let filt4 = v.iter().filter(|x: &&String| { (***x).contains("t") });

    // Fails with error: type 'str' cannot be dereferenced
    // let filt5 = v.iter().filter(|x| { (****x).contains("t") });

}
pramodbiligiri
  • 355
  • 1
  • 10
  • 1
    An `&&String` is a reference to a reference to a pointer to an `str` (String is a smart pointer). Therefore you can deref' though three levels of pointers before you reach something which is *not* a pointer, and thus can't be dereferenced. – Masklinn Sep 15 '20 at 12:15

0 Answers0