Why are type annotations needed?
⚓ Rust 📅 2026-06-03 👤 surdeus 👁️ 1When I have functions depending on common data, a pattern I often use is:
impl Data {
fn new() -> Self {
Self { x: vec![1.; 10] }
}
fn f(&self, _x: &[f64], _y: &mut [f64]) {
/* todo */
}
// ...
}
However, if I have a generic function run such as:
trait FDF { /* todo */ }
impl<F> FDF for F where F: FnMut(&[f64], &mut [f64]) {}
fn run(_fdf: impl FDF) { /* todo */ }
the call
let d = Data::new();
run(|x, y| d.f(x, y));
fails to compile. I have to annotate the closure:
let d = Data::new();
run(|x: &[f64], y: &mut [f64]| d.f(x, y));
Any reason why I have to do that? (There is a single possibility for the type of the closure, whence my surprise.)
4 posts - 3 participants
🏷️ Rust_feed