From 64f5de463558832bdc79b8df3143fd078c369386 Mon Sep 17 00:00:00 2001 From: Mike Verdone Date: Tue, 13 Jan 2015 14:57:19 +0100 Subject: [PATCH] Implement ignore function on Result. Fixes #20949 --- src/libcore/result.rs | 31 +++++++++++++++++++++++++++++++ src/libcoretest/result.rs | 9 +++++++++ 2 files changed, 40 insertions(+) diff --git a/src/libcore/result.rs b/src/libcore/result.rs index f7421203336c3..acaae658c3c66 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -157,6 +157,17 @@ //! } //! ``` //! +//! If you are absolutely sure you want to ignore a result, you must +//! do so explicitly: +//! +//! ```{.no_run} +//! # use std::io::{File, Open, Write}; +//! +//! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write); +//! file.write_line("important message").ignore(); +//! # drop(file); +//! ``` +//! //! # The `try!` macro //! //! When writing code that calls many functions that return the @@ -353,6 +364,26 @@ impl Result { } } + /// Ignore this result. + /// + /// Converts `self` into (), consuming `self`, and + /// discarding the value or error. + /// + /// # Example + /// + /// ``` + /// let x: Result = Ok(2); + /// x.ignore(); + /// ``` + #[inline] + #[stable] + pub fn ignore(self) { + match self { + Ok(_) => (), + Err(_) => (), + } + } + ///////////////////////////////////////////////////////////////////////// // Adapter for working with references ///////////////////////////////////////////////////////////////////////// diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index 485549cc552ac..b81bc0ab26fe5 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -139,3 +139,12 @@ pub fn test_unwrap_or_else_panic() { let bad_err: Result = Err("Unrecoverable mess."); let _ : int = bad_err.unwrap_or_else(handler); } + +#[test] +pub fn test_ignore() { + let ok: Result = Ok(100i); + let ok_err: Result = Err("Err"); + + ok.ignore(); + ok_err.ignore(); +}