I have encountered a situation where creating a function which returns a closure leaves me very confused as to why one syntax direction refuses to compile whereas another is allowed. I don't actually care about the functionality of the underlying code, as I'm merely analyzing it to better understand the language. Any direction as to an understanding why these two functions behave differently would be much appreciated.
Approach 1: The "Correct" Approach
fn legal_function<'a>(s: &'a String) -> impl Fn(String) -> bool + 'static
{
let y = s.clone();
let closure = move |x| {
return x == y;
};
return closure;
}
Approach 2: My Personally "Preferred" Yet "Incorrect" Approach
fn illegal_function<'a, T>(s: &'a String) -> T
where
T: Fn(String) -> bool + 'static,
{
let y = s.clone();
let closure = move |x| {
return x == y;
};
return closure;
}
The compiler gives the error every closure has a distinct type and so could not always match the caller-chosen type of parameter 'T'
I could accept that the function refuses to compile with any type ambiguity and BOTH the above functions refuse to compile. I am having a very difficult time accepting that for some reason Approach 1's ambiguity is allowed to compile from clearly SOME sort of type inference logic, and yet Approach 2's ambiguity is not allowed when the inner code blocks are identical. Thank you for your time if you read all this!