Closure type inference

I get
:8:17: 8:22 error: the type of this value must be known in this context
:8 let f = |x| x.col;

Is this a bug or am I missing something?

Rust Playground u forget add Coord type to closure
it is the same as u write function
fn myfunct(x) {x} without type info

@Codenator81,
Usually rust infers the argument/return types of closures and rust has enough information to infer the type of this closure.

Interestingly, this works but this has the same issue.

Maybe because the type of f can be Fn(T) -> R or Fn(&T) -> R or Fn(&mut T) -> R. Due to the auto-deref feature, there is no possible way to choose one or the other. When f is passed to the function, the compiler must type-check f and it can not since there are 3 possibilities available: the type of f must be more precise. In the second example, the closure is directly passed to the function and so the problem does not arise. Not sure about this explanation but it would make sense :smile:

I'm passing by value, so it can't be &mut because that's passing a mutable reference

Of course you pass by value but, in spirit, it could work if you passed it by ref or mut-ref, thanks to the auto-dereference feature. I think the compiler wants you to be sure to prevent some kind of errors. For example:

struct AutoDerefInt { data: i32 }

impl AutoDerefInt {
  pub fn update(&mut self, x: i32) {
    self.data = x;
  }
}

fn main(){
    let f = |x| x.update(9);
    let mut x = AutoDerefInt { data: 1 };
    // Without the type of `f`, the compiler could accept both of the following, but the behavior is completely different! This is error prone!
    f(&mut x);
    f(x);
}