]> git.lizzy.rs Git - rust.git/commitdiff
Improved example code in Option
authorAdolfo OchagavĂ­a <aochagavia92@gmail.com>
Sun, 11 May 2014 16:23:46 +0000 (18:23 +0200)
committerAlex Crichton <alex@alexcrichton.com>
Tue, 13 May 2014 02:52:29 +0000 (19:52 -0700)
src/libcore/option.rs
src/libstd/option.rs

index fd6d174a7036e29edd2481ef3b01ad94691515d8..886b7315152b8e1eb54bbe94f32051ebf9adbf80 100644 (file)
 //! of a value and take action, always accounting for the `None` case.
 //!
 //! ```
-//! # // FIXME This is not the greatest first example
-//! // cow_says contains the word "moo"
-//! let cow_says = Some("moo");
-//! // dog_says does not contain a value
-//! let dog_says: Option<&str> = None;
+//! 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 (cow_says, dog_says) {
-//!     (Some(cow_words), Some(dog_words)) => {
-//!         println!("Cow says {} and dog says {}!", cow_words, dog_words);
-//!     }
-//!     (Some(cow_words), None) => println!("Cow says {}", cow_words),
-//!     (None, Some(dog_words)) => println!("Dog says {}", dog_words),
-//!     (None, None) => println!("Cow and dog are suspiciously silent")
+//! match result {
+//!     // The division was valid
+//!     Some(x) => println!("Result: {}", x),
+//!     // The division was invalid
+//!     None    => println!("Cannot divide by 0")
 //! }
 //! ```
 //!
index 8fbcd529b63b7a6abfa1449c8d6b4e17a1e3d5ab..ad834f2b4d44bcac4723c0be951e147d316b6904 100644 (file)
 //! of a value and take action, always accounting for the `None` case.
 //!
 //! ```
-//! # // FIXME This is not the greatest first example
-//! // cow_says contains the word "moo"
-//! let cow_says = Some("moo");
-//! // dog_says does not contain a value
-//! let dog_says: Option<&str> = None;
+//! 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 (cow_says, dog_says) {
-//!     (Some(cow_words), Some(dog_words)) => {
-//!         println!("Cow says {} and dog says {}!", cow_words, dog_words);
-//!     }
-//!     (Some(cow_words), None) => println!("Cow says {}", cow_words),
-//!     (None, Some(dog_words)) => println!("Dog says {}", dog_words),
-//!     (None, None) => println!("Cow and dog are suspiciously silent")
+//! match result {
+//!     // The division was valid
+//!     Some(x) => println!("Result: {}", x),
+//!     // The division was invalid
+//!     None    => println!("Cannot divide by 0")
 //! }
 //! ```
 //!