'C equivalent x-macro defined enum in Rust

I have been a C/C++ developer for more years than I care to remember. I am now starting out in Rust. Based on reading the documentation, I believe it will be able to address most, if not all, of my needs directly. However, I want to make sure that I can understand the Rust equivalent syntax for the following C++ syntax (I skipped error checking code for simplicity)

#include <iostream>
#include <map>

#define MY_ENUM \
  X(AA, 17) \
  X(BB, 42)

enum my_enum {
#define X(name, val) name = val,
  MY_ENUM
#undef X
};

std::string enum_to_str(my_enum x)
{
  static std::map<int, std::string> lookup = { 
#define X(name, val) {val, #name},
  MY_ENUM
#undef X
  };  
  return lookup.at(x);
}

my_enum str_to_enum(const std::string &x) 
{
  static std::map<std::string, my_enum> lookup = { 
#define X(name, val) {#name, my_enum(val)},
  MY_ENUM
#undef X
  };  
  return lookup.at(x);
}

int main()
{
  my_enum x = AA; 
  const std::string bb("BB");
  std::cout << "x=" << x << " which is " << enum_to_str(x) << std::endl;
  std::cout << bb << " is " << str_to_enum(bb) << std::endl;
}

I believe I can achieve the to_string() functionality using either the Display or Debug trait in Rust, like so.

#[derive(Debug)]
enum MyEnum {
    AA = 17, 
}

//use std::fmt;
//impl fmt::Display for MyEnum {
//    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//       write!(f, "{:?}", self)
//    }
//}

fn main() {
    let x = MyEnum::AA;
    println!("x={:?}", x); 
}

What would be a way to do the string_to_enum() in Rust?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source