From 7baae03c8f145262692a4154a9ae64e3ad637d9e Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Wed, 20 Apr 2016 16:39:39 +0200 Subject: [PATCH] impl From for () MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I use the `try!` macro a lot, usually with `()` as the error type since I don’t care that much about tracking data about errors. When using some existing function or method that returns `Result` with a different error type, I find myself using code like this: ```rust try!(foo.map_err(|_| ())) ``` … which is more verbose than I’d like. The `try!` macro already uses the `From` trait to convert errors, some implementations like `impl From for ()` would help. But rather than adding them one by one to many error types, a generic solution would be nice. --- src/libcore/convert.rs | 7 +++++++ src/libcoretest/tuple.rs | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index 2d999868f71ec..d9501de7fe8e2 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -216,6 +216,13 @@ impl From for T { fn from(t: T) -> T { t } } +// A (the) value of the unit type can be created from any value of any type. +// This is useful for use with the `try!` macro or the `?` operator. +#[stable(feature = "unit_from_anything", since = "1.10.0")] +impl From for () { + fn from(t: T) -> () {} +} + //////////////////////////////////////////////////////////////////////////////// // CONCRETE IMPLS //////////////////////////////////////////////////////////////////////////////// diff --git a/src/libcoretest/tuple.rs b/src/libcoretest/tuple.rs index 4fe5e0a740bf7..7bcd0863183ed 100644 --- a/src/libcoretest/tuple.rs +++ b/src/libcoretest/tuple.rs @@ -66,3 +66,13 @@ fn test_show() { let s = format!("{:?}", (1, "hi", true)); assert_eq!(s, "(1, \"hi\", true)"); } + +#[test] +fn test_convert_unit_from_any() { + fn io() -> Result { Ok(1) } + fn fmt() -> Result { Ok(2) } + fn sum() -> Result { + Ok(io()? + try!(fmt())) + } + assert_eq!(sum(), Ok(3)) +}