The rust type system - elegant and simple
Rust has an elegeant type system. To declare a type is as easy as this:
Now that we have MyType, we can use it as an argument to a function, a return type, or anywhere else that you would use a primitive or struct.
The big advantage this confers is safety. I’d like to illustrate this with an aside into programming history, based on a very worthwile read.
Apps Hungarian was a useful way to help prevent common programming errors. Programmers would include a short description of what a variable’s type should be in the name, so an integer representing a relative coordinate in the x-axis might have a name like BoxMinSz_RelX. On seeing the statement
It is clear that you are comparing a relative and absolute coordinate, and that this is likely an error.
Hungarian notation got a terrible reputation because the useful technique above is not what people learned as hungarian notation. They learned to write this:
Which doesn’t add any new and useful semantic information, just bloat.
Defining a type in rust enforces the first case. You can’t pass an u32 where a MyType is expected. This eliminates a whole class of bugs, and in rust it is a zero cost abstraction, so it’s not the wasteful object wrapping you would get in something like Java where one would typically write
which turns a primitive into an object, adding references, indirection and increasing storage size.
Thanks for reading. If you have any questions, suggestions, or to point out any mistakes, please contact me at the email address below. I’d love to hear from you.