Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to obtain Prost! enum from String

The generated enum type looks like this, although I don’t really have access to the src as it’s generated by Prost! during the build:

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum Fruit {
    Unspecified = 0,
    Apple = 1,
    Banana = 2,
    Lemon = 3,
    ...

I can get a &str from an enum like this:

let apple = Fruit::Apple;
assert_eq!(apple.as_str_name(), "APPLE");

This method is provided by Prost!.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But I want to get the enum from a string.

The strum crate offers a solution except I can’t edit the source code file. Maybe there’s a hack using include!() to attach a macro annotation during the build stage.

>Solution :

prost_build can be configured to attach arbitrary attributes to the generated code via type_attribute and field_attribute:

// build.rs

Config::new()
    .type_attribute("Fruit", "#[derive(EnumString)]")
    .compile_protos(["src/fruit.proto"], &["src"])
    .unwrap();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading