Option:告别空指针

学习目标

读完这一节,你会用 Option 表达“可能没有值”;用 map、unwrap_or、expect 取值或给默认值;用 and_then 和 ? 串联可能失败的步骤;还会知道 unwrap 什么时候能用。

上一节练习答案

上一节的练习是写“成绩单处理”程序:grade 用 if let 取分再用 match 加守卫评级,None 返回“缺考”;first_pass 用 while let 配迭代器返回第一个及格分。参考答案:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn grade(score: Option<u32>) -> &'static str {
    if let Some(s) = score {
        match s {
            x if x >= 90 => "优秀",
            x if x >= 80 => "良好",
            x if x >= 60 => "及格",
            _ => "不及格",
        }
    } else {
        "缺考"
    }
}

fn first_pass(scores: &[u32]) -> Option<u32> {
    let mut iter = scores.iter();
    while let Some(&n) = iter.next() {
        if n >= 60 {
            return Some(n);
        }
    }
    None
}

fn main() {
    println!("{}", grade(Some(95)));
    println!("{}", grade(Some(72)));
    println!("{}", grade(None));
    println!("{:?}", first_pass(&[45, 58, 61, 90]));
    println!("{:?}", first_pass(&[30, 40]));
}

运行结果:

1
2
3
4
5
优秀
及格
缺考
Some(61)
None

练习里留的两个问题:grade 为什么用 if let 不用 match?因为只有“有分数”一种情况要展开处理,None 一句话返回,if let 更省事。while let 怎么知道该停?next() 取完返回 None,模式匹配不上,循环就停了。

核心概念

空指针的代价

很多语言用空指针表示“没有值”:一个变量要么指向对象,要么是 null。问题是编译器不检查判空,忘了判,程序跑到一半就崩了。发明空指针的 Tony Hoare 后来把这个设计称为“十亿美元的错误”。

Rust 把“可能没有值”写进类型里:Option<T> 要么是 Some(T),要么是 None,编译器逼你先处理 None,再用里面的值。

Option 的定义

Option 是标准库里的一个枚举,定义只有两行:

1
2
3
4
pub enum Option<T> {
    None,
    Some(T),
}

T 是泛型参数,装什么类型都可以:Some(5) 是 Option<i32>,Some("你好") 是 Option<&str>。None 本身不带类型信息,必须写上类型,比如 let absent: Option<i32> = None;。

取值:match、map 与默认值

Option 里有值,最直接的取法是 match,两个分支一个都不能少;只关心一种情况,就用上一节的 if let。

map 在有值时把值换个样子,没值就原样返回 None:

1
2
3
4
let name: Option<&str> = Some("hello");
name.map(|s| s.to_uppercase()); // Some("HELLO")
let nothing: Option<&str> = None;
nothing.map(|s| s.to_uppercase()); // None

map 不碰 None,也不展开 Some,只是“有值就加工,没值就放过”。

没值的时候想给个默认值,用 unwrap_or:

默认值算起来贵,用 unwrap_or_else,闭包现算,只有 None 时才执行。unwrap_or_default 用类型默认值,比如数字是 0。

expect 和 unwrap 都是“没有值就 panic”,区别是 expect 能留一句话说明原因。

串联:and_then 与 ? 运算符

一个步骤可能失败,下一步又依赖它:先按 id 查用户,查到再查邮箱,任何一步是 None,整个结果就是 None。and_then 就是干这个的:前一个是 Some,就把里面的值交给下一个返回 Option 的函数;前一个是 None,就直接短路返回 None。

? 是更顺手的写法:写在返回 Option 的函数里,遇到 None 直接返回 None,遇到 Some 取出值继续往下写。两种写法效果一样。

只看一眼:as_ref 与 filter

Option 里装 String 这种值,map 会把值拿走,之后原变量不能用了。as_ref 先借引用再 map,只看一眼不拿走。

filter 给 Option 加个条件:满足就留下,不满足就变成 None。两个 Option 都要同时有值才继续,可以把它们放进元组一起 match,缺一个就落到 None。

可运行代码

第一个程序:Option 的基本用法——创建、匹配、map:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
fn main() {
    let some_number = Some(5);
    let some_string = Some("你好");
    let absent: Option<i32> = None;

    println!("{:?}", some_number);
    println!("{:?}", some_string);
    println!("{:?}", absent);

    match some_number {
        Some(n) => println!("有值:{}", n),
        None => println!("没有值"),
    }

    let name: Option<&str> = Some("小优");
    println!("大写:{:?}", name.map(|s| s.to_uppercase()));

    let nothing: Option<&str> = None;
    println!("大写:{:?}", nothing.map(|s| s.to_uppercase()));
}

运行结果:

1
2
3
4
5
6
Some(5)
Some("你好")
None
有值:5
大写:Some("小优")
大写:None

去掉 Option<i32> 标注,None 就编不过——编译器猜不出它装的是什么类型。

第二个程序:unwrap_or、expect、unwrap 的对比:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
fn main() {
    let config: Option<&str> = None;
    println!("配置:{}", config.unwrap_or("默认配置"));

    let score: Option<u32> = Some(92);
    println!("分数:{}", score.unwrap_or(0));

    let mode: Option<&str> = None;
    println!("模式:{}", mode.unwrap_or_else(|| "从环境读取"));

    let port: Option<u16> = Some(8080);
    println!("端口:{}", port.expect("端口必须配置"));

    // unwrap:只在确定有值时用
    let answer: Option<i32> = Some(42);
    println!("答案:{}", answer.unwrap());
}

运行结果:

1
2
3
4
5
配置:默认配置
分数:92
模式:从环境读取
端口:8080
答案:42

unwrap_or 的默认值在 Some 时也不会被用上;expect 在有值时和 unwrap 一样,只有 None 时才 panic 并打印那句话。

第三个程序:and_then 串联,再用 ? 写一遍:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
fn find_user(id: u32) -> Option<&'static str> {
    match id {
        1 => Some("小优"),
        2 => Some("阿杰"),
        _ => None,
    }
}

fn user_email(name: &str) -> Option<String> {
    match name {
        "小优" => Some("xiaoyou@example.com".to_string()),
        "阿杰" => Some("ajie@example.com".to_string()),
        _ => None,
    }
}

fn email_of(id: u32) -> Option<String> {
    find_user(id).and_then(user_email)
}

// 用 ? 运算符写同一个逻辑
fn email_of_q(id: u32) -> Option<String> {
    let name = find_user(id)?;
    user_email(name)
}

fn main() {
    println!("{:?}", email_of(1));
    println!("{:?}", email_of(2));
    println!("{:?}", email_of(99));
    println!("{:?}", email_of_q(1));
    println!("{:?}", email_of_q(99));
}

运行结果:

1
2
3
4
5
Some("xiaoyou@example.com")
Some("ajie@example.com")
None
Some("xiaoyou@example.com")
None

id 是 99 时,find_user 返回 None,and_then 直接短路,user_email 没被调用;? 的版本也一样。

第四个程序:filter、as_ref、两个 Option 一起匹配:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn main() {
    let n = Some(7);
    println!("偶数吗:{:?}", n.filter(|x| x % 2 == 0));
    let m = Some(8);
    println!("偶数吗:{:?}", m.filter(|x| x % 2 == 0));

    // as_ref:只看一眼,不拿走
    let name = Some(String::from("小优"));
    let len = name.as_ref().map(|s| s.len());
    println!("名字长度:{:?}", len);
    // name 还能用,因为 as_ref 只借了引用
    println!("名字还在:{:?}", name);

    // 两个都有值才继续
    let a = Some(3);
    let b = Some(4);
    let sum = match (a, b) {
        (Some(x), Some(y)) => Some(x + y),
        _ => None,
    };
    println!("和:{:?}", sum);
}

运行结果:

1
2
3
4
5
偶数吗:None
偶数吗:Some(8)
名字长度:Some(6)
名字还在:Some("小优")
和:Some(7)

名字长度 是 6 不是 2:String::len() 算的是字节数,“小优”两个汉字占 6 个字节。

常见坑

  • None 不写类型:let x = None; 编译不过,必须写类型标注。
  • 滥用 unwrap:写时觉得“这里一定有值”,上线后偏偏没有,unwrap 一 panic,整个程序跟着崩。能用 unwrap_or、expect 就别用 unwrap。
  • map 包出双层 Option:闭包返回的是 Option,map 会再包一层,得到 Option<Option<T>>。串联可能失败的步骤用 and_then,不是 map。
  • ? 用在不返回 Option 的函数里:? 只能用在返回 Option(或 Result)的函数里。
  • filter 的闭包拿的是引用:filter(|x| ...) 里 x 是 &T,比较时记得这一点。
  • unwrap_or 的默认值每次都会算:unwrap_or(expensive()) 里 expensive() 不管有没有值都会先执行一次,默认值贵的时候改用 unwrap_or_else。

动手练习

写“用户资料查找”程序:

  1. find_user(id: u32) -> Option<&'static str>:1 返回 Some("小优"),2 返回 Some("阿杰"),其他返回 None。
  2. user_age(name: &str) -> Option<u32>:"小优" 返回 Some(25),"阿杰" 返回 Some(30),其他返回 None。
  3. 用 and_then 把上面两个函数串成 age_of;再用 ? 写一个 age_of_q,实现同样的逻辑。
  4. main 里测试 age_of(1)、age_of(2)、age_of(99),打印结果。
  5. 回答:age_of(99) 返回 None 的过程中,user_age 被调用了吗?为什么?map 和 and_then 选错了会发生什么?

提示:and_then 的闭包要返回 Option,user_age 正好符合,可直接传函数名。

小结与预告

核心就一句话:Option 把“可能没有值”写进类型里,编译器逼你处理 None;有值就 map,没值就给默认值或短路返回,串联用 and_then 或 ?,别随便 unwrap。

下一节 7.2:Vec 与字符串操作。Option 解决“有没有”,Vec 解决“有多少个”——下一节看动态数组怎么增长、怎么遍历。


配套练习:在学习站动手练这一节

本文代码基于 Rust 1.8x / Edition 2024 验证。

JerryHome · 记录技术与生活