Wednesday, February 6, 2019
Sum type with Enum in Rust programming language
Enum - Enumeration
Enumeration as user defined data type and in C programming language its mainly used for names to integral constants .
C syntax:
Enum state { success = 1, failed = 0 };
Enums has very limited usage in C language. But Rust has used all use cases for Enum and adopted lot of use cases from Functional programming languages like Haskell and ML.
Rust Enum Syntax:
enums are the best example for Sum types. If you want to restrict the input to any one of the types which defined , then they are called some types.
Say you have 'Shape' Type, and you know that shape can be only Circle ,Square or Rectangle. You want to do action for each types separately. then you can go with Enum.
sum type aslo called Tagged Union, is a data structure used to hold a value that could take on several different, but fixed, types. Only one of the types can be in use at any one time, and a tag field explicitly indicates which one is in use.
The primary advantage of a tagged union/sum type over an untagged union is that all accesses are safe, and the compiler can even check that all cases are handled.
Enum Shape{
Circle(f32),
Square(f32),
Rectangle(f32,f32),
}
Enum example
Product type:
Struct is good example for product type. As we know, it is required to provide values for each types in a struct . It will be cartesian product of combinations we can make on struct types. It is must to provide value for each for defining an object.
Importance of enum :
As I mentioned earlier, enum allows to define our own types which increase the readability
of the code as well as reduce the type issues in the programs.
For example , when we know we can only pass our defined type to function and if we can give a meaningful name for that type , which improve strength of the type system in our programs as well as improve the readability of the code.
if parent type consist of different child types, then it will be nice to use them with the hierarchy .Since it is not a product type, you can use one of them from parent at a time. For different type of input can do type validation and perform corresponding action.
No comments:
Post a Comment