14

I have an enum:

enum Group {
    OfTwo {
        first: usize,
        second: usize,
    },
    OfThree {
        one: usize,
        two: usize,
        three: usize,
    },
}

I would like to write a function that only takes as argument the Group::OfTwo variant:

fn proceed_pair(pair: Group::OfTwo) {}

But when I do that, I get the message:

error[E0573]: expected type, found variant `Group::OfTwo`
  --> src/lib.rs:13:23
   |
13 | fn proceed_pair(pair: Group::OfTwo) {}
   |                       ^^^^^^^^^^^^
   |                       |
   |                       not a type
   |                       help: try using the variant's enum: `crate::Group`

Is there a way to achieve this?

1 Answer 1

21

The variants of an enum are values and all have the same type - the enum itself. A function argument is a variable of a given type, and the function body must be valid for any value of that type. So what you want to do will just not work.

However, there is a common pattern for designing enums, which might help here. That is, to use a separate struct to hold the data for each enum variant. For example:

enum Group {
    OfTwo(OfTwo),
    OfThree(OfThree),
}

struct OfTwo { first: usize, second: usize }
struct OfThree { one: usize, two: usize, three: usize }

fn proceed_pair(pair: OfTwo) {

}

Anywhere that you previously matched on the enum like this:

match group {
    Group::OfTwo { first, second } => {}
    Group::OfThree { first, second, third } => {}
}

You would replace with:

match group {
    Group::OfTwo(OfTwo { first, second }) => {}
    Group::OfThree(OfThree { first, second, third }) => {}
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.