[Rust] Enum

enum Color {
    Red,
    Green,
    Blue,
    Yellow,
}

impl Color {
    fn is_green(&self) -> bool {
        if let Color::Green = self {
            return true;
        }

        return false;
    }

    fn is_green_parts(&self) -> bool {
        match self {
            Color::Red => false,
            Color::Blue => true,
            Color::Yellow => true,
            Color::Green => true,
        }
    }
}

fn print_color(color: Color) {
    match color {
        Color::Red => println!("Red"),
        Color::Green => println!("Green"),
        Color::Blue => println!("Blue"),
        Color::Yellow => println!("Yellow"),
    }
}


fn main() {

    print_color(Color::Blue);
    print_color(Color::Red);
    print_color(Color::Green);
    print_color(Color::Yellow);

    let foo = Color::Green;
    foo.is_green();
}

Cool thing about Enum in Rust, when you append a new enum value, for example Pink, it will automatcilly tells you that in matchblock, you missed Pink.

In Typescript, there is no such benifits provdied automaticlly, it requires you doing something

enum Color {
  Red,
  Green,
  Blue,
  Yellow,
}

function main(color: Color) {
  switch (color) {
    case Color.Red:
      console.log("red");
      break;
    case Color.Blue:
      console.log("blue");
      break;
    case Color.Green:
      console.log("green");
      break;
    default:
      assertNever(color); // Error, you need to add case for Yellow
  }
}

function assertNever(value: never) {
  throw new Error(`Unexpected value: ${value}`);
}

 

posted @   Zhentiw  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-05-17 [Cloud DA] Serverless Framework with AWS
2021-05-17 [AWS] Using APIGateway to validate API request
2020-05-17 [React Recoil] Write a Custom Recoil Hook to Reset a Value in the Recoil State
2019-05-17 [Functional Programming] propSatisfies with implies
2019-05-17 [Git] How to revert one file changes from one commit
2019-05-17 [Svelte 3] Use reactive declarations to compute component state in Svelte 3
2018-05-17 [Javascript] Deep Search nested tag element in DOM tree
点击右上角即可分享
微信分享提示