3 ms·
> the length of the array is being inferred based on the type provided in the assertion Wow! I hate that with an amount of emotion that surprised me! Does Rus
by happytoexplain 3y ago
> the length of the array is being inferred based on the type provided in the assertion
Wow! I hate that with an amount of emotion that surprised me!
Does Rust do this kind of look-ahead inference a lot (specifically for deciding what the result shape/type is for a statement)?
- kibwen 3y ago> Does Rust do this kind of look-ahead inference a lot Yes, but it's important to note that type inference in Rust is function-local. Furthermore, crucially, Rust requires types to be explicitly specified at function boundaries. Altogether this means that you (and the compiler) don't need to look farther than the function signature to figure out a given type. This means that you can do stuff like this: let mut foo = HashMap::new(); foo.insert("bar", true); Despite the fact that HashMap is a generic type, nowhere do we need to specify that this particular instance has string keys and Boolean values, because the type of the map is inferred from its usage. In languages with only statement-local type inference, you'd need to specify the type of the elements at the point of construction.
- happytoexplain 3y agoThis isn't so bad except in the case where a developer puts off the resolving statement until later in the function, though I imagine (hope) there is almost never a legitimate reason to do that. Is it theoretically possible to split the resolution into two lines? Then, as a reader, it might not always be obvious at what point the type is fully resolved. E.g (pseudocode, and also it makes no practical sense since you would have populated it before interrogating it). let mut foo = HashMap::new(); print(foo.containsKey("bar")); // here we've resolved the key type print(foo.containsValue(true)); // here we've resolved the value type
- bestouff 3y agoOf course yes.
- kibwen 3y ago> Then, as a reader, it might not always be obvious at what point the type is fully resolved. This is rarely a problem, because Rust is strict enough that it will tell you if your types aren't lining up like you think they are. And if you're using an editor with LSP support, then you can have inlay hints that reveal the types of all variables if you like.
- happytoexplain 3y ago> inlay hints that reveal the types Oh, that would go a long way to making me feel less nervous reading code like this.