Reputation: 53037
In Haskell, it is possible, as a language feature, to derive a parser from a string to an arbitrary datatype: that's called the Read
class. Is it possible to do so in Rust? That is, given an arbitrary enum
such as:
#[derive(Debug)]
enum Foo {
A { x: u32, s: String },
B { v: Vec<u8> },
}
and, given that Rust includes the Debug
trait as a language feature that serializes an arbitrary datatype, is it possible to also automatically generate its corresponding Parse
trait?
In other words, is there a default Rust feature that allows me to derive a parse(&str) -> Foo
function such that, for any string s
either parse(&s) == None
or format!("{:?}", parse(&s).unwrap()) == s
?
Upvotes: 2
Views: 277
Reputation: 431679
No, there is no such feature. Debug
is intended for human/programmer consumption, not for machines.
There's no guarantee that the Debug
output is even in a parseable format or that it contains the complete data of a type.
I recommend using Serde instead, paired with an existing defined serialization format of your choice.
If you wanted to, you could define your own derive
attributes that implement Debug
and FromStr
by calling into Serde.
Upvotes: 5