1、首先要晓得什么是Option和Result
起源:
许多语言应用null/nil/undefined类型来代表空的输入和解决异样谬误。Rust跳过了,特地是避免空指针异样之类的问题,因为异样等起因导致敏感数据透露等等。相同,Rust提供了两个非凡的类枚举:Option和Result就是来解决以上的问题
内容:
- 可选的值要么是Some要么是没有值/None
Result要么用胜利/Ok要么是失败/Err
// An output can have either Some value or no value/ None.enum Option<T> { // T is a generic and it can contain any type of value. Some(T), None,}// A result can represent either success/ Ok or failure/ Err.enum Result<T, E> { // T and E are generics. T can contain any type of value, E can be any error. Ok(T), Err(E),}
并且不须要独自引入它们
Option的根底用法:
在写一个函数或者数据类型的时候:- 如果一个函数的参数是可选的
- 如果函数是非空的并且输入的返回可能不是空值
- 如果一个值,活着是一个属性的数据类型可能是空
2、咱们不得不应用Option作为它们的数据类型
例如,一个函数的输入可能是&str类型或者是输入是空,函数的返回类型能够被设置为 Option<&str>
fn get_an_optional_value() -> Option<&str> { //if the optional value is not empty return Some("Some value"); //else None}
struct Name { first_name: String, middle_name: Option<String>, // middle_name can be empty last_name: String,}
参考:https://learning-rust.github.io/docs/e3.option_and_result.html
注:以上是集体学习的过程中翻译的,可能有些翻译不对,请见谅,欢送斧正