Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type alias for enum

Tags:

rust

Is there a way to make the code below work? That is, export an enum under a type alias, and allow access to the variants under the new name?

enum One { A, B, C }

type Two = One;

fn main() {
    // error: no associated item named `B` found for type `One` in the current scope
    let b = Two::B;
}
like image 573
Tim Robinson Avatar asked Nov 08 '15 23:11

Tim Robinson


People also ask

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

What is an enum TypeScript?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.

What is enum in rust?

An enum in Rust is a type that represents data that is one of several possible variants. Each variant in the enum can optionally have data associated with it: #![allow(unused_variables)] fn main() { enum Message { Quit, ChangeColor(i32, i32, i32), Move { x: i32, y: i32 }, Write(String), }

What is enum in MVC?

In MVC 5.1, HTML helper class EnumDropDownListFor has been introduced which is used to display the Enum in a dropdown as shown in the image below: To start with let us consider that we have created an Enum TypeOfStudent as shown in the listing below. This Enum holds information about the type of a particular student. 1.


1 Answers

I don't think type aliases allow doing what you want, but you can rename the enum type in a use statement:

enum One { A, B, C }

fn main() {
    use One as Two;
    let b = Two::B;
}

You can use this in combination with pub use to re-export types under a different identifier:

mod foo {
    pub enum One { A, B, C }
}

mod bar {
    pub use foo::One as Two;
}

fn main() {
    use bar::Two;
    let b = Two::B;
}
like image 90
fjh Avatar answered Oct 08 '22 03:10

fjh