3 ms·
`!` is binary negation for integers. `return x` is an expression that can be used in place of any type because it will never be used.
by pitaj 5y ago
`!` is binary negation for integers. `return x` is an expression that can be used in place of any type because it will never be used.
- masklinn 5y ago> `return x` is an expression that can be used in place of any type because it will never be used. To clarify: the expression will run, but it has the type `!` ("never"). And while that's still not a "proper" rust type (other uninhabited types are though they may not be quite as special-cased in the compiler), it is in essence a bottom type: since it can't have a value, it will unify with any type. That's why Rust is perfectly happy with let foo = if a { 1 } else { return 42 }; The first branch has type `{integer}`, the second branch has type `!`. `!` unifies just fine with `{integer}`, therefore the typechecker is happy.
- OJFord 5y agoWhaat, was this new in 2018 ed? I could've sworn it was `()` and so you couldn't do that. I don't write rust that often, and happen to be reading this just as I've written some code that's.. not that messy but not that I'm pleased with, wrangling around exactly this sort of if-assign-else-return pattern.
- steveklabnik 5y agoI don’t believe it should be new, but this can happen by accident sometimes. Like, if you included a ; on the non-return branch it would return () overall and you probably thought the return did it when it wasn’t that. Hard to say!
- OJFord 5y agoI made exactly that error when I went back to refactor with my new-found knowledge, so I think that must have been it. Thanks, both of you! /facepalm
- steveklabnik 5y agoGlad to hear it!
- orthoxerox 5y ago() is a unit type, it has a single possible value. ! has no possible values.