Skip to content

Commit 351fefb

Browse files
committed
add fn core::convert::id<T>(x: T) -> T { x }
1 parent 0f9c784 commit 351fefb

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

src/libcore/convert.rs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,73 @@
5050

5151
use fmt;
5252

53+
/// An identity function. Two things are important to note about this function:
54+
///
55+
/// - It is not always equivalent to a closure like `|x| x` since the
56+
/// closure may coerce `x` into a different type.
57+
///
58+
/// - It moves the input `x` passed to the function.
59+
///
60+
/// While it might seem strange to have a function that just returns back the
61+
/// input, there are some interesting uses.
62+
///
63+
/// # Examples
64+
///
65+
/// Using `id` to do nothing among other interesting functions:
66+
///
67+
/// ```rust
68+
/// #![feature(convert_id)]
69+
/// use std::convert::id;
70+
///
71+
/// fn manipulation(x: u32) -> u32 {
72+
/// // Let's assume that this function does something interesting.
73+
/// x + 1
74+
/// }
75+
///
76+
/// let _arr = &[id, manipulation];
77+
/// ```
78+
///
79+
/// Using `id` to get a function that changes nothing in a conditional:
80+
///
81+
/// ```rust
82+
/// #![feature(convert_id)]
83+
/// use std::convert::id;
84+
///
85+
/// // Let's pretend we have an interesting condition:
86+
/// let condition = true;
87+
///
88+
/// let do_stuff = if condition { manipulation } else { id };
89+
///
90+
/// // do more interesting stuff..
91+
/// let _results = do_stuff(42);
92+
/// ```
93+
///
94+
/// Using `id` to concatenate an iterator of iterators:
95+
///
96+
/// ```rust
97+
/// #![feature(convert_id)]
98+
/// use std::convert::id;
99+
///
100+
/// let vec_vec = vec![vec![1, 3, 4], vec![5, 6]];
101+
/// let iter_iter = vec_vec.into_iter().map(Vec::into_iter);
102+
/// let concatenated = iter_iter.flat_map(id).collect::<Vec<_>>();
103+
/// assert_eq!(vec![1, 3, 4, 5, 6], concatenated);
104+
/// ```
105+
///
106+
/// Using `id` to keep the `Some` variants of an iterator of `Option<T>`:
107+
///
108+
/// ```rust
109+
/// #![feature(convert_id)]
110+
/// use std::convert::id;
111+
///
112+
/// let iter = vec![Some(1), None, Some(3)].into_iter();
113+
/// let filtered = iter.filter_map(id).collect::<Vec<_>>();
114+
/// assert_eq!(vec![1, 3], filtered);
115+
/// ```
116+
#[unstable(feature = "convert_id", issue = "0")]
117+
#[inline]
118+
pub fn id<T>(x: T) -> T { x }
119+
53120
/// A type used as the error type for implementations of fallible conversion
54121
/// traits in cases where conversions cannot actually fail.
55122
///

0 commit comments

Comments
 (0)