3 ms·
The primitive type inference is helpful, especially given the number of `val as i32` conversions that one might encounter when doing arithmetic from different c
by nevi-me 7y ago
The primitive type inference is helpful, especially given the number of `val as i32` conversions that one might encounter when doing arithmetic from different crates. It however feels "magical", so I'm not sure of how I feel about it.
Do the primitive type inferences also work when comparing i32 vs &i32, or even better, &i32 vs &u64?
- steveklabnik 7y agoYes, all combos of &T and T on both sides of the operator do. Sorry for not being more explicit about that in the post!
- simias 7y agoI believe that this only works for literal type inference, i.e.: let a: f32 = 0.0; let b: f64 = 0.0; let this_works: f32 = &0.0 + 0.0; let this_doesnt: f32 = &a + b; And that's a good thing IMO, implicit promotion rules in C are one of my least favourite features of the language. It makes it so easy to write seemingly innocuous code that's completely broken.
- steveklabnik 7y agoYes, it is only for literals.
- djrenren 7y agoThis seems like an odd choice... do you know the rationale? (or have a link to an issue/RFC I could go read)
- steveklabnik 7y agoI am finding it a bit tough to explain concisely, maybe go check out https://github.com/rust-lang/rust/pull/68129/ https://github.com/rust-lang/rust/pull/68129/ and it might help?
- majewsky 7y agoIt's becoming a recurring pattern in newer languages that number literals are their own magical type (usually backed by a bigint or bigfloat) that only coerce into a concrete type when they first come into contact, so to say, with a typed variable or expression.
- kibwen 7y agoThough note that the implementation in Rust is much less magical than that of, say, Go. Every numeric literal expression has a concrete type. When that type can be inferred from context (using the ordinary type inference rules), it is. When it can't be inferred from context, the compiler forces integer literals to i32 and float literals to f64; if that causes additional type errors to occur, then Rust requires the user to insert type annotations where necessary rather than trying to be smart about it (this can all be observed in the error messages in the OP). IOW, code using the numeric literal fallback types only compiles when it makes no semantic difference what the type is (modulo `unsafe`, as ever). This mostly happens in small code examples and test cases/doctests, e.g. `fn main() { dbg!(42); }` only compiles because of the existence of this fallback.
- ridiculous_fish 7y agoWhat is &0.0 + 0? Adding a reference to a float to a float - is it being automatically dereferenced?
- steveklabnik 7y agoYes, it is being automatically de-referenced.