What is enum
What is Rust Enum?
A custom data type called an enum has some fixed values in it. The name of the enumeration appears before an enum keyword in its definition. It also includes techniques.
syntax of enum:
enum enum_name
{
variant1,
variant2,
.
.
}
The enum name in the syntax above is enum_name, and the enum values associated with the enum name are variant1, variant2,…
Example:
enum Computer_language
C,
C++,
Java,
The enum name in the sample above is computer_language, and its values are C, C++, and Java.
Enum values
Now let’s make an instance of every variation. It appears as follows:
let c = Computer_language :: C;
let cplus = Computer_language :: C++;
let java = Computer_language :: Java;
The three instances, c, cplus, and java, in the scenario above are created with the values C, C++, and Java, respectively. Double colons are utilized, and each form of enum has been namespaced under its identifier. Because Computer_language::C, Computer_language::C++, and Computer_language::Java are all members of the same type Computer_language this is helpful.
Another option is to define a function on a specific instance. Now that the function that accepts an instance of type Computer_language has been defined, it appears as follows:
fn language_type(language_name::Computer_language);
Any of the following variations can be used to call this function:
language_type(Computer_language :: C++);
Example:
#[derive(Debug)]
enum Employee {
Name(String),
Id(i32),
Profile(String),
}
fn main() {
let n = Employee::Name("Hema".to_string());
let i = Employee::Id(2);
let p = Employee::Profile("Computer Engineer".to_string());
println!(" {:?} s {:?} b {:?}", n,i,p);
}
Output:
Name("Hema") s Id(2) b Profile("Computer Engineer")
The custom data type Employee in the example above has three variants: Name (String), Id (i32), and Profile (String). To print the instance of each variant, use the “:?”