Hi all,
I'm trying to use a generic function pointer with a trait bound, and pass it to a function:
use std::fs::File;
use std::io::{BufRead, BufReader};
type ReaderFn<R: BufRead> = fn(R);
fn read_file<R: BufRead>(rdr: R) {
for line in rdr.lines() {
println!("{}", line.unwrap());
}
}
fn call<R: BufRead>(func: ReaderFn<R>) {
let f = File::open("/tmp").unwrap();
let rdr = BufReader::new(f);
// this works
read_file(rdr);
// this doesn't
func(rdr);
}
But I've got this error:
error[E0308]: mismatched types
--> src/main.rs:20:10
|
12 | fn call<R: BufRead>(func: ReaderFn<R>) {
| - this type parameter
...
20 | func(rdr);
| ^^^ expected type parameter `R`, found struct `BufReader`
|
= note: expected type parameter `R`
found struct `BufReader<File>`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`
To learn more, run the command again with --verbose.
I don't know why it works calling a simple func but not with the function pointer. I tried with a
F: Fn ->
kind of construct but no success.
Any idea ?
Thanks a lot.