4 ms·
Yes. That's thanks to Hindley-Milner type inference which makes the compiler infer which None you mean. But in longer code snippets full Hindley-Milner type inf
by yakubin 3y ago
Yes. That's thanks to Hindley-Milner type inference which makes the compiler infer which None you mean. But in longer code snippets full Hindley-Milner type inference can cause hard-to-understand type errors. Here specifically the compiler infers the type of a value in your function body based on the type of the function it belongs to, which is in the opposite direction than what a programmer typically thinks in. It leads to spooky actions at a distance.
- kibwen 3y ago> It leads to spooky actions at a distance. I'll disagree on "spooky". If the type is ambiguous, the code will fail to compile. Contrapositively, that means that if the code compiles, the types aren't ambiguous. I find bidirectional type inference to be absolutely lovely (or at least Rust's implementation of it), and I wouldn't give it up.
- stefncb 3y agoIt's actually not. There's simply a 'use Option::{None, Some}' built-in to make them easier to work with.
- estebank 3y agoThe GP is referencing cases where inference can't figure out what the T is in Option::<T>::None. This can happen in the body of a closure without an explicit return type, for example. To solve it you have to specify the type either earlier in a place that helps inference (in the example, add a return type) or in the expression, like None::<()>.
- stefncb 3y agoYeah sorry I apparently can't read, it was pretty obvious. Thanks.
- diarrhea 3y agoAs another poster said, None is in the prelude. It’s been explicitly imported, just… implicitly so. Other than that, Rust places strong emphasis on function signatures. They override everything else, such as inferred return types from the function body. This is to ease composition and reading (as far as I remember). That is to say, in Rust it is quite natural to refer back to the function definition, potentially to let it do inference heavy lifting, or work with the question mark operator. It doesn’t feel the wrong way.
- estebank 3y ago> But in longer code snippets full Hindley-Milner type inference can cause hard-to-understand type errors. I would love to see examples of this. We've gotten much better on this front over the years, but I'm sure there are plenty of cases yet to be addressed. The "problem" with improving error messages is that the common and easy cases are addressed early, leaving only the uncommon and difficult to address left after a while, and people get used to the understandable errors which leaves them baffled when they encounter one that isn't.