|
48 | 48 |
|
49 | 49 | #![stable(feature = "rust1", since = "1.0.0")]
|
50 | 50 |
|
| 51 | +/// An identity function. |
| 52 | +/// |
| 53 | +/// 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 `identity` to do nothing among other interesting functions: |
| 66 | +/// |
| 67 | +/// ```rust |
| 68 | +/// #![feature(convert_id)] |
| 69 | +/// use std::convert::identity; |
| 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 = &[identity, manipulation]; |
| 77 | +/// ``` |
| 78 | +/// |
| 79 | +/// Using `identity` to get a function that changes nothing in a conditional: |
| 80 | +/// |
| 81 | +/// ```rust |
| 82 | +/// #![feature(convert_id)] |
| 83 | +/// use std::convert::identity; |
| 84 | +/// |
| 85 | +/// # let condition = true; |
| 86 | +/// |
| 87 | +/// # fn manipulation(x: u32) -> u32 { x + 1 } |
| 88 | +/// |
| 89 | +/// let do_stuff = if condition { manipulation } else { identity }; |
| 90 | +/// |
| 91 | +/// // do more interesting stuff.. |
| 92 | +/// |
| 93 | +/// let _results = do_stuff(42); |
| 94 | +/// ``` |
| 95 | +/// |
| 96 | +/// Using `identity` to keep the `Some` variants of an iterator of `Option<T>`: |
| 97 | +/// |
| 98 | +/// ```rust |
| 99 | +/// #![feature(convert_id)] |
| 100 | +/// use std::convert::identity; |
| 101 | +/// |
| 102 | +/// let iter = vec![Some(1), None, Some(3)].into_iter(); |
| 103 | +/// let filtered = iter.filter_map(identity).collect::<Vec<_>>(); |
| 104 | +/// assert_eq!(vec![1, 3], filtered); |
| 105 | +/// ``` |
| 106 | +#[unstable(feature = "convert_id", issue = "53500")] |
| 107 | +#[rustc_const_unstable(feature = "const_convert_id")] |
| 108 | +#[inline] |
| 109 | +pub const fn identity<T>(x: T) -> T { x } |
| 110 | + |
51 | 111 | /// A cheap reference-to-reference conversion. Used to convert a value to a
|
52 | 112 | /// reference value within generic code.
|
53 | 113 | ///
|
|
0 commit comments