Rust开发—— 枚举与Option枚举

前言

枚举可以为程序带来有利于安全的输入处理,并通过给枚举变量一个名称来为类型添加上下文。在 rust 中,最常见到的枚举是Option和Result。Rust 中的枚举相比于的其它语言(C类语言)有很大的灵活性。它可以包含许多数据类型,如元组、结构等,枚举也可以异构。此外,还可以像struct一样对枚举实现方法。枚举模式匹配是rust语言最重要的功能之一。

枚举

1.普通定义枚举

enum Gender 
{
    
    
    male,
    female,
    neutrois,
}

2.使用枚举

fn main() 
{
    
    
    let f : Gender = Gender::female;
    get_gender(f);
}
fn get_gender(gender : Gender)
{
    
    
    print!("{:?} \n",gender);
}
  1. 异构的枚举
#[derive(Debug)]
enum IpAddr 
{
    
    
    V4(u8, u8, u8, u8), 
    V6(String), 
}

fn main() 
{
    
    
    
    let V4 = IpAddr::V4(127, 0, 0, 1);
  
    let V6 = IpAddr::V6("::1".to_string());
    get_ipaddr(V4);
    get_ipaddr(V6);
    
}

fn get_ipaddr(ip : IpAddr)
{
    
    
    println!("{:?}\n",ip);
}

4.匹配枚举
使用 match 关键字可以对 enum 进行模式匹配。

fn matcher(x : Gender) 
{
    
    
    match x
    {
    
    
        Gender::female => print!("Gender is female"),
        Gender::male =>print!("Gender is male"),
        Gender::neutrois =>print!("Gender is neutrois"),
    }    
}

给 matcher 函数传递一个枚举值,函数会把匹配到的输出:

fn main() 
{
    
    
    let f : Gender = Gender::female;
    matcher(f);
}

5.给枚举定义方法

#[derive(Debug)]
enum Gender 
{
    
    
    male,
    female,
    neutrois,
}

impl Gender
{
    
    
    fn call(&self)
    {
    
    
        print!("{:?}",self);
    }
}

let f : Gender = Gender::female;
f.call();

Option枚举

1.Option枚举原型

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

Option < T > 是一个包含两个值的枚举: None 和 Some (T)。“None”可以被认为是没有任何值,而“Some”(T)可以被认为是存在某个值。这里的T是一个泛型,意思就是任何类型。只是“ T”作为一个约定使用,也可使用别的字母代替。Option枚举是为避免空空指针的出现。

  1. 使用 Option 这个枚举是 rust 为了不使用 null 值和异常,假设,要去判断一个字符串的是否为空,要用C++实现则:
String str = "";
if(str == null)
{
    
    
	------
}
else
{
    
    
	-------
}

如果是new出来的变量,变量为空时要释放则会出现异想不到的问题,rust是为了避免使用null而设计的Option 枚举。使用rust实现上面的例子:

 let str : Option<String> = None;
    
    match str
    {
    
    
        Some(v) =>  println!("We go something: {}", v),
        None => println!("We got nothing"),
    }
    
  1. unwrap
    当对一个值进行调用时,使用“unwrap”可能获取 Some 变量中的值。如果存在 Some 有值,则值为该类型并返回。如果存在“None”变体,则引发恐慌:
let something: Option<&str> = Some("Something");
let unwrapped = something.unwrap(); 
println!("{:?}\n{:?}", something, unwrapped);
let nothing: Option<&str> = None;
nothing.unwrap();
  1. 让函数返回一个Option枚举
fn contains_char(text: String, target_c: char) -> Option<String> 
{
    
    
    if text.chars().any(|ch| ch == target_c)
    {
    
    
        return Some(text);
    } 
    else 
    {
    
    
        return None;
    }
}

let a = contains_char("Rust in action".to_string(), 'a');
let q = contains_char("Rust in action".to_string(), 'q');
println!("{:?}", a);
println!("{:?}", q);

5.Option做为参数传入函数

fn might_print(option: Option<&str>) 
{
    
    
    match option 
    {
    
    
        Some(text) => println!("The argument contains the following value: '{}'", text),
        None => println!("The argument contains None."),
    }
}
let something: Option<&str> = Some("some str");
let nothing: Option<&str> = None;
might_print(something);
might_print(nothing);
  1. 结构体中的Option枚举
#[derive(Debug)]
struct Person 
{
    
    
    name: String,
    age: Option<i32>,
}

let marie = Person 
{
    
    
    name: String::from("matt"),
    age: Some(2),
};

let jan = Person 
{
    
    
    name: String::from("mora"),
    age: None,
};
println!("{:?}\n{:?}", marie, jan);

猜你喜欢

转载自blog.csdn.net/matt45m/article/details/126337336