Option
Option<T> の使用方法についてはすでにいくつか見てきましたが、これは型 T の値を格納するか、何も格納しません。たとえば、String::find は Option<usize> を返します。
fn main() { let name = "Löwe 老虎 Léopard Gepardi"; let mut position: Option<usize> = name.find('é'); println!("find returned {position:?}"); assert_eq!(position.unwrap(), 14); position = name.find('Z'); println!("find returned {position:?}"); assert_eq!(position.expect("Character not found"), 0); }
This slide should take about 10 minutes.
-
Optionis widely used, not just in the standard library. -
unwrapはOption内の値を返すか、パニックになります。expectも同様ですが、エラーメッセージを受け取ります。- None でパニックになる場合もありますが、「誤って」None のチェックを忘れることはありません。
- 何かを一緒にハッキングする場合は、あちこちで
unwrap/expectを行うのが一般的ですが、本番環境のコードは通常、Noneをより適切に処理します。
-
The “niche optimization” means that
Option<T>often has the same size in memory asT, if there is some representation that is not a valid value of T. For example, a reference cannot be NULL, soOption<&T>automatically uses NULL to represent theNonevariant, and thus can be stored in the same memory as&T.