References in generic functions

use std::path::PathBuf;

fn testfn() {
    let rd = std::fs::read_dir(PathBuf::from("path")).unwrap();
    rd.filter(fake); // error
    //rd.filter(|v| fake(v)); // ok
    //rd.filter(fake2); // ok
}

fn fake<P>(_: P) -> bool {
    true
}

fn fake2<P>(_: &P) -> bool {
    true
}

fn main() {
    println!("Hello");
}

please tell me why rd.filter(fake) is not compiled?

in

fn fake<P>(_: P) -> bool {
    true
}

the parameter P can be instantiated as &type. or not?

Here's an earlier thread with an explanation.

TL;DR:

Yes it can, but that will result in a concrete reference type with a concrete lifetime. In contrast, the signature of filter() demands that the function be higher-ranked over the lifetime. This works when it is a closure or when it explicitly accepts a reference (because the compiler treats reference-typed function arguments specially), but a generic type parameter can't be instantiated to a higher-ranked reference; for<'a> &'a T is simply not a type (or a thing).

2 Likes

okay, thank you very much

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.