Hey there,
The code on the main function bellow works just fine, but when I try to do something similar on a trait implementation, it can't figure out the trait bounds of my closure, at least that's what I think is going on. What am I doing wrong here ?
#![allow(dead_code)]
struct Closures<F> {
list: Vec<F>
}
impl<F> Closures<F>
where
F: FnOnce() -> Result<(), &'static str>
{
fn new() -> Self {
Self { list: Vec::new() }
}
fn add(&mut self, f: F) -> &mut Self {
self.list.push(f);
self
}
}
fn main(){
let mut closures = Closures::new();
closures.add(|| {
if true {
Ok(())
} else {
Err("An error")
}
});
for closure in &closures.list {
match closure() {
Ok(_) => println!("OK!"),
Err(err) => println!("{err}")
}
}
}
pub trait ClosureList {
fn closures<F>(&self) -> Closures<F>
where
F: FnOnce() -> Result<(), &'static str>;
}
struct Test;
impl ClosureList for Test {
fn closures<F>(&self) -> Closures<F>
where
F: FnOnce() -> Result<(), &'static str>
{
let mut closures = Closures::new();
closures.add(|| {
if true {
Ok(())
} else {
Err("An error")
}
});
closures
}
}
Error:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/main.rs:62:9
|
48 | fn closures<F>(&self) -> Closures<F>
| - ----------- expected `Closures<F>` because of return type
| |
| this type parameter
...
54 | closures.add(|| {
| -- the found closure
...
62 | closures
| ^^^^^^^^ expected type parameter `F`, found closure
|
= note: expected struct `Closures<F>`
found struct `Closures<[closure@src/main.rs:54:22: 54:24]>`
= help: every closure has a distinct type and so could not always match the caller-chosen type of parameter `F`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error