Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use existing types in an enum in Rust

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?

like image 961
Chris Middleton Avatar asked Jan 13 '16 10:01

Chris Middleton


People also ask

How do you match enums 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.

Can enums have methods Rust?

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.

How do you convert enum to string in Rust?

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.

How do I extend an enum in Rust?

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 => ... }


1 Answers

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

like image 175
Paolo Falabella Avatar answered Sep 18 '22 18:09

Paolo Falabella