Programming Languages – Why Does Type Go After Variable Name?

language-designprogramming-languagessyntax

Why is it that in nearly all modern programming languages (Go, Rust, Kotlin, Swift, Scala, Nim, even Python last version) types always come after the variable name in the variable declaration, and not before?

Why x: int = 42 and not int x = 42?
Is the latter not more readable than the former?
Is it just a trend or are there any really meaningful reasons behind this solution?

Best Answer

All of the languages you mentioned support type inference, which means the type is an optional part of the declaration in those languages because they're smart enough to fill it in themselves when you provide an initialization expression that has an easily-determined type.

That matters because putting the optional parts of an expression farther to the right reduces parsing ambiguity, and increases consistency between the expressions that do use that part and the ones that don't. It's just simpler to parse a declaration when you know the var keyword and the variable name are both mandatory before you get to the optional stuff. In theory, all of those things which make it easier to parse for computers should improve overall readability for humans too, but that's a lot more debatable.

This argument gets especially strong when you consider all the optional type modifiers that a "non-modern" language like C++ has, such as * for pointers, & for references, const, volatile and so on. Once you throw in commas for multiple declarations, you start to get some really strange ambiguities like int* a, b; not making b a pointer.

Even C++ now supports "type on the right" declarations in the form of auto x = int{ 4 };, and it does have some advantages.