Is type inference good for Rust?

When I saw the following code snippet, I was confusing what the type of buf。Although with IDE I got it is u8 immediately, is that good? so implicit thing in rust, without of the tip of IDE, when one wants get type of buf, he has to find where buf is used, "Oh it is first used in buf |= byte - b'A' + 10", so buf is the type of u8. And for b, one has to find the fact that b is used for the return value to realize its type is Vec<u8>. When writing code is so easy, reading code is so hard, especiall in this code snippet, when buf is u8, the method will not get the right thing.

Inference is necessary for Rust, because it has some types that can’t even be named (closures) and some types that are incredibly long and complex (Iterator chains, Futures chains).

It’s up to the author to use clear naming of variables and add type annotations where the types are not clear.


Looking at the type signature of the function helps a lot in situations like these. You see that it returns a Result<Vec<u8>, FromHexError>, so from there you can deduce that the function is likely going to be manipulating and collecting u8s.

That being said the naming scheme used in that function could be better, which would also help with discerning the types. b is a pretty nondescriptive name, and buf would be better used as the name for a Vec<u8> rather than a single u8

My experience, in a number of languages, is that once you get used to it it’s better.

For example, in C# I used to think that var was bad, and that I really wanted to see the types all the time. But then I switched to a team that used var heavily, and found that I really didn’t care about the completely-specific type most of the time. The domain concept, which is typically clear from the variable name, was absolutely sufficient.

For the same thing in C++, see

It does mean that you sometimes should do things like let mut x = 0_u32; or whatever when you actually care, but forcing types all the time is the wrong solution to needing them sometimes. (I even do var foo = (string)null; in C# instead of string foo = null; because I like the consistent declaration order, AAA-style, so much.)


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.