Hello
So I have an enum with values, I want to convert that string-value to a enum. Kind of like Java's .valueOf().
Rust didn't seemed to have anything built-in, so I tried using an external crate. I used the crates custom_derive and enum_derive as explained in this Stackoverflow answer.
This is my code:
#[macro_use]
extern crate custom_derive;
#[macro_use]
extern crate enum_derive;
#[derive(EnumFromStr)]
pub enum MyEnum {
A,
B,
}
struct MyStruct {
myStr : String,
myEnum : MyEnum,
}
fn main() {
let valueToConvert : String = "A".to_string();
let x : MyStruct = MyStruct {
myStr: "Blablabla".to_string(),
myEnum: valueToConvert.parse().unwrap(),
};
}
This is the error I get:
Compiling cat_generator v0.1.0 (/Users/niel/School/Rust/cat_generator)
error: cannot find derive macro EnumFromStr
in this scope
--> src/main.rs:6:10
|
6 | #[derive(EnumFromStr)]
| ^^^^^^^^^^^
warning: unused `#[macro_use]` import
--> src/main.rs:1:1
|
1 | #[macro_use]
| ^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: unused `#[macro_use]` import
--> src/main.rs:3:1
|
3 | #[macro_use]
| ^^^^^^^^^^^^
error[E0277]: the trait bound `MyEnum: std::str::FromStr` is not satisfied
--> src/main.rs:22:32
|
22 | myEnum: valueToConvert.parse().unwrap(),
| ^^^^^ the trait `std::str::FromStr` is not implemented for `MyEnum`
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0277`.
error: could not compile `cat_generator`.
To learn more, run the command again with --verbose.
I am doing exactly the same as the Stackoverflow answer, so what is going wrong? Also, is there another way to achieve this? Without using a match statement for all enum-values...?
Side-question:
Is there a way to compile external crates without using a whole cargo-project by just using a signle rs-file and rustc?
I need to define a path when using rustc --extern but to what exactly? Where can I download rlibs?
Thanks!