What Are Enums In Rust?

 What Are Enums In Rust?

What Are Enums In Rust?

Defining Enums

Enumerations or Enums are custom data types that allow us to define a sort by enumerating its possible values.
Example:
IP Addresses:
Version 4 or Version 6
The property of being V4 or V6 at a time make enum structures appropriate, because enum values can only be one among the variants.
But both versions are still IP Addresses and can be treated because an equivalent type.

Code it:

enum IpAddrKind {
V4
V6 Variants
}

Creating Instances:

#! [allow(unused_variables)]
fn main() {
enum IpAddrKind {
V4,
V6, }
let four = IpAddrKind::V4;
let six = IpAddrKind::V6; }

Defining & Calling a Function:

We can define a function that takes any IpAddrkind and
can call it with either of its variant.
#![allow(unused_variables)]
fn main() {
enum IpAddrKind {
V4,
V6,
}

Where’s the Data?

We’ve just learnt the way to make Enums and to make instances and defining and calling functions.
But we’ve not stored any data in last example.
So we will add data using structs and by another ways..

Adding Data Using Structs:

enum IpAddrKind {
V4,
V6,
}
struct IpAddr {
kind: IpAddrKind,
address: String,
}
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from(“127.0.0.1”),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from(“::1”),
};

A Concise Way Using an Enum:

                                            Hurray!

We’ve finally used structs to somehow associate values with the
variants.
                                            BUT

We can do the same thing during a more concise way using just an
enum.

Adding Data Using Enums:

This new definition of the IpAddr enum says that both V4 and V6 variants will have associated String values.

enum IpAddr {
V4(String),
V6(String),
}
let home = IpAddr::V4(String::from(“127.0.0.1”));
let loopback = IpAddr::V6(String::from(“::1”))

An Advantage Against Struct:

Each variant can have differing types and amounts of associated data in enums.

enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from(“::1”));

Standard Library Definition for IpAddr:

As we wanted to store IPaddresses and encode which sort they’re is so common
that the quality library features a definition we will use! Let’s check out how the quality library defines IpAddr.
struct Ipv4Addr {
// –snip–
}
struct Ipv6Addr {
// –snip–
}
enum IpAddr {
V4(Ipv4Addr),
V6(Ipv6Addr),
}

Is This A Win For Any Data Type!

Yes! The previous codes shown us that we’ll put any quite data inside an Enum Variant. We can even include Enums!

Another Example:

A message enum which features an enormous sort of types embedded in its variants.

enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
Same Thing Using Structs:
Defining an enum with variants is nearly almost like defining different

kinds of struct definitions.

struct QuitMessage; // unit struct
struct MoveMessage {
x: i32,
y: i32,
}
struct WriteMessage(String); // tuple struct
struct ChangeColorMessage(i32, i32, i32); //
tuple struct

So Enums are Easy!

Because if we use different structs which have differing kinds than we couldn’t as easily define a function to need any of these sorts of messages as we could with the Message enum which itself is simply single type.

One More Similarity: “Impl Block”

Just as we’re able to define methods on structs using impl, we’re also able to define methods on enums.
impl Message {
fn call(&self) {
// method body would be defined here
}
}
let m = Message::Write(String::from(“hello”));
m.call();

The “Option” Enum:

The “Option” enum is another enum defined by the quality library. the choice type is used in many places because it encodes the quite common scenario during which a worth could be something or it’d be nothing.

Null Feature for Languages:

Null could also be a worth meaning there is no value there. In languages with null, variables can always be in one among two states: null or not-null.

Problem?

The problem with null values is that if you’re trying to use a null value as a not-null value, you’ll get a mistake of some kind. Because this null or not-null property is pervasive, it’s extremely easy to make this sort of error.

Does Rust have Nulls?

No! However, the concept that null is trying to precise remains a useful one: a null may be a value that’s currently invalid or absent for some reason.

So, What does Rust have?

Enum! which will encode the concept of a worth being present or absent. This enum is “Option”, and it is defined within the standard library. The “Option” Enum Defined by Std. Lib: The Option enum is so useful that it’s even included within the prelude; you don’t need to bring it into scope explicitly. In addition, so are its variants: you’ll use 

Some and None directly without the
Option:: prefix. the choice enum remains
just a daily enum, and Some(T) and None are still variants of type Option.
enum Option
{
Some(T),
None,
}}
Example:
Here we’ve an example of using Option values to hold number types and string types. If we use None instead of Some, we need to tell Rust what sort of Option we’ve , because the compiler can’t infer the sort that the Some variant will hold by looking only at a None value.

let some_number = Some(5);
let some_string = Some(“a string”);
let absent_number: Option = None;

So Why Option is best than having Null?

Because Option and T (where T are often any type) are different types, the compiler won’t allow us to use an Option value as if it were definitely a legitimate value. sort of a code which is trying to feature an i8 to an Option won’t compile and can give a mistake because Rust doesn’t understand the way to add an i8 and an Option, because they’re differing types .

let x: i8 = 5;
let y: Option = Some(5);
let sum = x + y;

That’s How We Code Safely and Confidently!

In order to possess a worth which can possibly be null, we must explicitly opt in by making the sort of that value Option. Everywhere that a value features a type that isn’t an Option, we will safely assume that the value isn’t null. That’s how Rust increases the security of code.

1 thought on “What Are Enums In Rust?”

Leave a Comment