'a' => X when parsing and X => 'a' when printing -- in one place?


When parsing various inputs, e.g. when every char from the command line becomes one specific enum, I often use something like this:

let X = match c {
  'r' => Data::Color(Color::Red),
  '1' => Data::Number(Base::Ten),
  // .. etc

When printing some output I often have the exact inverse match case which results in char from an enum. So now I have the char <-> enum mapping present in two locations.

How can I remove this redundancy by only having the mapping present in one place and then use it for both char -> enum and enum -> char conversion?


This is a quite common problem.


You could do this pretty easily with a macro. Just have it take the map and spit out two conversion functions.