I listened to the Changelog podcast on Rust recently and loved the remark about enabling web developers to get into systems programming. I have been thinking about the way we design code in the web world versus the way we design code in Rust. In the web world, we often use a hash/dict/map to hide hard-coded values behind a nicer interface. Consider an example where you would want to write a function to create the escape sequence for colors in a TTY terminal. You might write something like this in Ruby:
The foreground and the background color codes are accessed by passing in the names of the color as a symbol via
color(:black, :white). If you tried to port this code directly into Rust, you would run into a few problems. First, there are no symbols in Rust. You might think to work around this by using strings instead of symbols. Then you start looking at the documentation for a HashMap and realize maps are quite a bit more involved than in Ruby. After fighting with the syntax for a while, you may come to the conclusion that Rust is too difficult of a language for you to figure out. There is a better way.
Rust has a really powerful feature called enums. Here is that same code using an enum:
You can call the color method via
color(ANSIColor::black, ANSIColor::white);. There is a complete, working example on playpen.
I think the use of enums in that code is really expressive. Even more so than ruby:
color(:black, :white). The Rust enum provides the context of what
white mean to the
color function. This also has the benefit of being type-checked by the compiler. If you or anyone else tries to specify a color like
ANSIColor::pink the compiler would generate an error for you. This removes the pain of checking for valid colors at runtime, handling those errors at runtime and writing tests around those use-cases. This compile-time checking is what makes Rust such a powerful language.
There are plenty of cases for using dicts/hashes/maps in Rust. However, if you find yourself writing a function that accepts a finite set of options, then I suggest trying to use a Rust enum before resorting to a HashMap.