gpt4 book ai didi

enums - 为什么我们使用 Option 枚举?

转载 作者:行者123 更新时间:2023-11-29 08:36:40 25 4
gpt4 key购买 nike

我不明白 Option 枚举的用途。我读到 Rust 没有空值。 Option 枚举定义如下:

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

我阅读了它的实现并遇到了这个例子:

fn main() {
fn divide(numerator: f64, denominator: f64) -> Option<f64> {
if denominator == 0.0 {
None
} else {
Some(numerator / denominator)
}
}

// The return value of the function is an option
let result = divide(2.0, 3.0);

// Pattern match to retrieve the value
match result {
// The division was valid
Some(x) => println!("Result: {}", x),
// The division was invalid
None => println!("Cannot divide by 0"),
}
}

当他们也可以这样做的时候:

fn main() {
fn divide(numerator: f64, denominator: f64) -> String {
if denominator == 0.0 {
format!("Can't divide")
} else {
let x = numerator / denominator;
format!("{}", x)
}
}

let result = divide(2.0, 3.0);
println!("{}", result);
}

两个程序输出:

0.6666666666666666

最佳答案

也许上面的例子不是Option的一个很好的例子, 但以下示例显示 Option处于最佳状态:

fn main() {
let name = String::from("naufil");
println!(
"Character at index 6: {}",
match name.chars().nth(6) {
Some(c) => c.to_string(),
None => "No character at index 6!".to_string(),
}
)
}

当我们不确定第 6 个元素是否有字符并且您不希望程序崩溃时,Option来救援。这是来自 The Rust Programming Language 的另一个示例:

fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}

let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);

Listing 6-5: A function that uses a match expression on an Option<i32>

Let’s examine the first execution of plus_one in more detail. When we call plus_one(five), the variable x in the body of plus_one will have the value Some(5). We then compare that against each match arm.

None => None,

The Some(5) value doesn’t match the pattern None, so we continue to the next arm.

Some(i) => Some(i + 1),

Does Some(5) match Some(i)? Why yes it does! We have the same variant. The i binds to the value contained in Some, so i takes the value 5. The code in the match arm is then executed, so we add 1 to the value of i and create a new Some value with our total 6 inside.

Now let’s consider the second call of plus_one in Listing 6-5, where x is None. We enter the match and compare to the first arm.

None => None,

It matches! There’s no value to add to, so the program stops and returns the None value on the right side of =>. Because the first arm matched, no other arms are compared.

Combining match and enums is useful in many situations. You’ll see this pattern a lot in Rust code: match against an enum, bind a variable to the data inside, and then execute code based on it. It’s a bit tricky at first, but once you get used to it, you’ll wish you had it in all languages. It’s consistently a user favorite.

关于enums - 为什么我们使用 Option 枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56504289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com