简体   繁体   English

Rust 中的 Some 和 Option 有什么区别?

[英]What is the difference between Some and Option in Rust?

Are they the same?他们是一样的吗? I can sometimes see the documentation use them as if they were equal.我有时可以看到文档使用它们,就好像它们是平等的一样。

The Option type is defined as: Option类型定义为:

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

Which means that the Option type can have either a None or a Some value.这意味着Option类型可以具有NoneSome值。

See also:也可以看看:

No, they are not the same, and documentation treating them as if they were the same is either wrong, or a misunderstanding on your side.不,它们不相同,并且将它们视为相同的文档要么是错误的,要么是您的误解。 Option is a type (more accurately, a generic type constructor ; Option<i32> is a type, and so is Option<String> ). Option是一种类型(更准确地说,是泛型类型构造函数Option<i32>是一种类型, Option<String>也是一种类型)。 Some is a constructor . Some是一个构造函数 Aside from acting as a function fn Some<T>(T x) -> Option<T> , it's also used in pattern matching:除了充当函数fn Some<T>(T x) -> Option<T> ,它还用于模式匹配:

let mut opt: Option<i32>; // type
opt = Some(1); // constructor
opt = None; // other constructor
match opt {
    Some(x) => {
        // pattern
        println!("Got {}", x);
    }
    None => {
        // other pattern
        println!("Got nothing");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM