Rust的模式匹配

文章目录

  • match匹配
  • if let匹配

match匹配

match可以结合枚举使用,例如

enum IpVersion {
	V4,
	V6,
}

fn ParseIpVersion(version: IpVersion) -> String {
    match version {
        IpVersion::V4 => String::from("ipv4"),
        IpVersion::V6 => String::from("ipv6"),
    }
}

match结合绑定值的枚举,例如

enum Ip {
	V4(String),
	V6(String),
}

fn ParseIpVersion(ip: Ip) {
    match ip {
        Ip::V4(ipv4) => println!("ipv4: {}", ipv4),
        Ip::V6(ipv6) => println!("ipv6: {}", ipv6),
    }
}

match必须列举所有的可能,在某些情况下可以使用占位符 _ 和通配 other 来保证列举所有可能

fn MatchNum0(num: i32) {
	match num {
		0 => println!("zero"),
		1 => println!("one"),
		_ => println!("other"),
	}
}

fn MatchNum1(num: i32) {
	match num {
		0 => println!("zero"),
		1 => println!("one"),
		other => println!("other: {}", other),
	}
}

可以使多个模式匹配一种结果

fn MatchNum(num: i32) {
	match num {
		0 | 1 => println!("zero or one"),
		_ => println!("other"),
	}
}

匹配结构体

struct User {
    age: u8,
    name: String,
    sex: char
}

fn MatchUser(user: User) {
	match user {
	    User { age: 10, name, sex } => println!("I'm {}, age is 10", if sex == '0' {"girl"} else {"boy"}),
	    User { age: 12, name, sex: '0' } => println!("I'm girl, age is 12"),
        _ => {println!("other age")}
	}
}

if let匹配

某些情况下可以使用if let这种匹配简单的匹配

fn MatchNum(num: Option<i32>) {
    if let Some(num ) = num {
        println!("number: {}", num)
    } else {
        println!("none")
    }
}

你可能感兴趣的:(rust,linux)