[Rust] Intro Enum

Go Enum

package main

type GoEnum = int
const (
    Foo GoEnum = iota
    Bar
    Baz
)

func main() {
}

 

Typescript Enum

enum TsEnum {
    Foo,
    Bar,
    Baz
}

 

Rust Enum

enum RsEnum {
    Foo,
    Bar,
    Baz
}

Why go over enums...

They are simple constructs. But you can add types to Rust Enum.

enum TsEnum {
    Foo(i32),
    Bar(String),
    Baz(Vec<String>)
}

Example:

enum TsEnum {
    Foo(i32),
    Fuu(Option<i32>),
    Bar(String),
    Baz(Vec<String>)
}

fn main() {
    // set value 5
    let foo = RsEnum::Foo(5);
    // pattern matching, pick the value
    if let RsEunm::Foo(value) = foo {
       
    }
    // or you can also do
    match foo {
       RsEnum::Foo(value) => {},
       RsEnum::Fuu(Some(value)) => { /* Has value */ },
       RsEnum::Fuu(None) => { /* Doesn't has value */ },
       _ => { /* Cover the rest cases */ }
    }
}

 

We can also do generic on them

enum Foo<T> {
    Bar(T)
}

 

How is this paractically useful?

  1. lists with many types
  2. Nullable
  3. Error Handling

Example of nullable in TS

type Foo = {
    bar?: string
}

function doSomething(foo: Foo): boolean {
   if (foo.bar) {
      return true
   } else {
      // ...
      return false
   }
}

in Rust

enum Option<T> {
    None,
    Some(T)
}

fn main () {
    let foo = Some(5)
    
    if let Some(value) = foo {
       // then value is i32
    }
    
    match foo {
        Some(value) => { /* value is i32*/ },
        None => {} 
    }
    
    // the same as in TS: foo.amp((x) => {})
    // do the transform fn only when there is a value
    foo.map(|x| => {
      
    })
    
    foo.filter(|&x| x < 10)
    
    if foo.is_some() {
       let sum = foo.unwrap() + 5;
    };
    
    foo.unwrap_or(0);
    
    foo.unwrap_or_else(|| {
        return 5
    })
}

 

posted @ 2024-02-12 16:04  Zhentiw  阅读(12)  评论(0)    收藏  举报