Say I have two structs:
struct BlankDoc {
width: u32,
height: u32
}
struct UrlDoc<'a> {
url: &str<'a>
}
Is there some way to use enums to make a Doc
type that will be either a BlankDoc
or a UrlDoc
, without having to reimplement (copy) all of their fields?
I was thinking something like this:
enum Doc {
&BlankDoc
&UrlDoc
}
or
type Doc = BlankDoc|UrlDoc;
(Obviously neither of these ways exist.)
What's the idiomatic way to model this in Rust?
Adding data to enum variants Created a new instance of the enum and assigned it to a variable. Put that variable in a match statement. Destructured the contents of each enum variant into a variable within the match statement. Used the destructed variable in the codeblock by the right of the pattern.
In Rust, methods cannot only be defined on structs, they can also be defined on tuples and enums, and even on built-in types like integers.
The easiest way to convert an enum to a String in Rust is to implement the std::fmt::Display trait. Then you can call the to_string() method.
An enum can't be directly extended, but you use the same composition trick one would use with structs (that is, with a struct, one would have a field storing an instance of the 'parent'). match some_extended { Base(Alpha) => ..., Base(Beta(x)) => ..., Gamma => ... }
You can wrap the existing structs in an enum. Eg
enum Doc<'a> {
Blank(BlankDoc),
Url(UrlDoc<'a>),
}
then you can do for instance:
fn test<'a>(doc: Doc<'a>) {
match doc {
Doc::Blank( BlankDoc { width: w, height: h }) =>
println!("BlankDoc with w:{}, h:{}", w, h),
Doc::Url( UrlDoc { url: u }) =>
println!("UrlDoc with url:{}", u),
}
}
full playground example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With