首页 > 其他分享 >[Rust] Enum

[Rust] Enum

时间:2023-05-17 15:00:39浏览次数:27  
标签:Blue Color Enum Yellow color Green Red Rust

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}`);
}

 

标签:Blue,Color,Enum,Yellow,color,Green,Red,Rust
From: https://www.cnblogs.com/Answer1215/p/17408764.html

相关文章

  • Python枚举类型enum
    为什么需要枚举枚举(Enum)是一种数据类型,也是一种特别的类,是绑定到唯一值的符号表示,可以使用它来创建用于变量和属性的常量集枚举类可以看成是一个下拉菜单,给出特定的选项且这些选项不可修改,更贴近自然语言的方式表达数据,可以让代码更容易阅读、维护,减少转换或者错误值引......
  • rust 中 str 与 String; &str &String
    StringString类型的数据和基本类型不同,基本类型的长度是固定的,所以可以在栈上分配,而String类型是变长的,所以需要在堆上分配,所以String类型实际上是一个指向堆的指针。他的结构和Vec很类似。从他的声明看也是一个u8的VecpubstructString{vec:Vec<u8>,}看这样一个定......
  • 用Rust实现DES加密/解密算法
    信息安全技术课程要求实现一下DES算法。对着一份Java代码断断续续抠了几天,算是实现出来了。这里记录一下算法思想和我的Rust实现。DES算法解析概述https://en.wikipedia.org/wiki/Data_Encryption_StandardDES是一种对称的分组加密算法,加密和解密使用同一个密钥,计算过程将数......
  • Rust 笔记 - 2
    结构体初始化Rust的结构体类似于C,使用关键字struct声明。structUser{active:bool,sign_in_count:u32,username:String,email:String}结构体中的每个元素称为“域”(field),域是可修改的(mutable),使用.来访问域的值。创建实例为了使用结构体,需要根据结......
  • [Rust] Collect()
    Stringcollect:automaticllycallingconcatonstringletfoo:String=vec!["this","is","a","test"].into_iter().collect();println!("{:?}",foo);//thisisatest HashSet:let......
  • Python - Enum
    官方文档:https://docs.python.org/zh-cn/3.11/library/enum.html#functional-api枚举的字面含义是指列出有穷集合中的所有元素,即一一列举的意思。可视为一种数据类型作用:具有数据保护功能,使常量不可更改。能避免数据重复创建枚举有两种方式:#classsyntaxclassColor(Enu......
  • 【计算几何】Rust求解平面最近点对(寻找距离最近的两个点的距离)
    目录题目地址代码题目地址https://ac.nowcoder.com/acm/contest/52826/C代码usestd::io;usestd::cmp::Ordering;usestd::f64;#[derive(Debug,PartialEq,PartialOrd,Clone,Copy)]structPoint{x:f64,y:f64,}fneuclidean_distance(p1:&Point,p2:......
  • IQueryable 和 IEnumerable
         ......
  • LINQ使用细节之.AsEnumerable()和.ToList()的区别
    先看看下面的代码,用了.AsEnumerable():1varquery=(fromaindb.Table2wherea=SomeCondition3selecta.SomeNumber).AsEnumerable();45 intrecordCount=query.Count();6 inttotalSomeNumber=query.Sum();7 decimalaverage=......
  • .AsEnumerable()和.ToList()的区别
    .AsEnumerable()延迟执行,不会立即执行。当你调用.AsEnumerable()的时候,实际上什么都没有发生。.ToList()立即执行当你需要操作结果的时候,用.ToList(),否则,如果仅仅是用来查询不需要进一步使用结果集,并可以延迟执行,就用.AsEnumerable()/IEnumerable /IQueryable.AsEnumerable()......