1
1
//! Traits for conversions between types.
2
2
//!
3
- //! The traits in this module provide a general way to talk about conversions
4
- //! from one type to another. They follow the standard Rust conventions of
5
- //! `as`/`into`/`from`.
3
+ //! The traits in this module provide a way to convert from one type to another type.
4
+ //! Each trait serves a different purpose:
6
5
//!
7
- //! Like many traits, these are often used as bounds for generic functions, to
8
- //! support arguments of multiple types.
6
+ //! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions
7
+ //! - Implement the [`AsMut`] trait for cheap mutable-to-mutable conversions
8
+ //! - Implement the [`From`] trait for consuming value-to-value conversions
9
+ //! - Implement the [`Into`] trait for consuming value-to-value conversions to types
10
+ //! outside the current crate
11
+ //! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`],
12
+ //! but should be implemented when the conversion can fail.
9
13
//!
10
- //! - Implement the `As*` traits for reference-to-reference conversions
11
- //! - Implement the [`Into`] trait when you want to consume the value in the conversion
12
- //! - The [`From`] trait is the most flexible, useful for value _and_ reference conversions
13
- //! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but allow for the
14
- //! conversion to fail
14
+ //! The traits in this module are often used as trait bounds for generic functions such that to
15
+ //! arguments of multiple types are supported. See the documentation of each trait for examples.
15
16
//!
16
- //! As a library author, you should prefer implementing [`From<T>`][`From`] or
17
+ //! As a library author, you should always prefer implementing [`From<T>`][`From`] or
17
18
//! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
18
19
//! as [`From`] and [`TryFrom`] provide greater flexibility and offer
19
20
//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
20
- //! blanket implementation in the standard library. However, there are some cases
21
- //! where this is not possible, such as creating conversions into a type defined
22
- //! outside your library, so implementing [`Into`] instead of [`From`] is
23
- //! sometimes necessary.
21
+ //! blanket implementation in the standard library. Only implement [`Into`] or [`TryInto`]
22
+ //! when a conversion to a type outside the current crate is required.
24
23
//!
25
24
//! # Generic Implementations
26
25
//!
@@ -99,28 +98,22 @@ use fmt;
99
98
#[ inline]
100
99
pub const fn identity < T > ( x : T ) -> T { x }
101
100
102
- /// A cheap reference-to-reference conversion. Used to convert a value to a
103
- /// reference value within generic code.
101
+ /// Used to do a cheap reference-to-reference conversion.
104
102
///
105
- /// `AsRef` is very similar to, but serves a slightly different purpose than,
106
- /// [`Borrow`].
103
+ /// This trait is similar to [`AsMut`] which is used for converting between mutable references.
104
+ /// If you need to do a costly conversion it is better to implement [`From`] with type
105
+ /// `&T` or write a custom function.
107
106
///
108
- /// `AsRef` is to be used when wishing to convert to a reference of another
109
- /// type.
110
- /// `Borrow` is more related to the notion of taking the reference. It is
111
- /// useful when wishing to abstract over the type of reference
112
- /// (`&T`, `&mut T`) or allow both the referenced and owned type to be treated
113
- /// in the same manner.
114
107
///
115
- /// The key difference between the two traits is the intention :
108
+ /// `AsRef` is very similar to, but serves a slightly different purpose than [`Borrow`] :
116
109
///
117
110
/// - Use `AsRef` when the goal is to simply convert into a reference
118
111
/// - Use `Borrow` when the goal is related to writing code that is agnostic to
119
112
/// the type of borrow and whether it is a reference or value
120
113
///
121
114
/// [`Borrow`]: ../../std/borrow/trait.Borrow.html
122
115
///
123
- /// **Note: this trait must not fail**. If the conversion can fail, use a
116
+ /// **Note: This trait must not fail**. If the conversion can fail, use a
124
117
/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
125
118
///
126
119
/// [`Option<T>`]: ../../std/option/enum.Option.html
@@ -134,7 +127,12 @@ pub const fn identity<T>(x: T) -> T { x }
134
127
///
135
128
/// # Examples
136
129
///
137
- /// Both [`String`] and `&str` implement `AsRef<str>`:
130
+ /// By using trait bounds we can accept arguments of different types as long as they can be
131
+ /// converted a the specified type `T`.
132
+ ///
133
+ /// For example: By creating a generic function that takes an `AsRef<str>` we express that we
134
+ /// want to accept all references that can be converted to &str as an argument.
135
+ /// Since both [`String`] and `&str` implement `AsRef<str>` we can accept both as input argument.
138
136
///
139
137
/// [`String`]: ../../std/string/struct.String.html
140
138
///
@@ -157,12 +155,13 @@ pub trait AsRef<T: ?Sized> {
157
155
fn as_ref ( & self ) -> & T ;
158
156
}
159
157
160
- /// A cheap, mutable reference -to-mutable reference conversion.
158
+ /// Used to do a cheap mutable-to-mutable reference conversion.
161
159
///
162
- /// This trait is similar to `AsRef` but used for converting between mutable
163
- /// references.
160
+ /// This trait is similar to [`AsRef`] but used for converting between mutable
161
+ /// references. If you need to do a costly conversion it is better to
162
+ /// implement [`From`] with type `&mut T` or write a custom function.
164
163
///
165
- /// **Note: this trait must not fail**. If the conversion can fail, use a
164
+ /// **Note: This trait must not fail**. If the conversion can fail, use a
166
165
/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
167
166
///
168
167
/// [`Option<T>`]: ../../std/option/enum.Option.html
@@ -176,10 +175,11 @@ pub trait AsRef<T: ?Sized> {
176
175
///
177
176
/// # Examples
178
177
///
179
- /// [`Box<T>`] implements `AsMut<T>`:
180
- ///
181
- /// [`Box<T>`]: ../../std/boxed/struct.Box.html
182
- ///
178
+ /// Using `AsMut` as trait bound for a generic function we can accept all mutable references
179
+ /// that can be converted to type `&mut T`. Because [`Box<T>`] implements `AsMut<T>` we can
180
+ /// write a function `add_one`that takes all arguments that can be converted to `&mut u64`.
181
+ /// Because [`Box<T>`] implements `AsMut<T>` `add_one` accepts arguments of type
182
+ /// `&mut Box<u64>` as well:
183
183
/// ```
184
184
/// fn add_one<T: AsMut<u64>>(num: &mut T) {
185
185
/// *num.as_mut() += 1;
@@ -189,7 +189,7 @@ pub trait AsRef<T: ?Sized> {
189
189
/// add_one(&mut boxed_num);
190
190
/// assert_eq!(*boxed_num, 1);
191
191
/// ```
192
- ///
192
+ /// [`Box<T>`]: ../../std/boxed/struct.Box.html
193
193
///
194
194
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
195
195
pub trait AsMut < T : ?Sized > {
@@ -198,29 +198,27 @@ pub trait AsMut<T: ?Sized> {
198
198
fn as_mut ( & mut self ) -> & mut T ;
199
199
}
200
200
201
- /// A conversion that consumes `self`, which may or may not be expensive . The
202
- /// reciprocal of [`From`][From ].
201
+ /// A value-to-value conversion that consumes the input value . The
202
+ /// opposite of [`From`].
203
203
///
204
- /// **Note: this trait must not fail**. If the conversion can fail, use
205
- /// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
206
- /// [`Result<T, E>`].
204
+ /// One should only implement [`Into`] if a conversion to a type outside the current crate is
205
+ /// required. Otherwise one should always prefer implementing [`From`] over [`Into`] because
206
+ /// implementing [`From`] automatically provides one with a implementation of [`Into`] thanks to
207
+ /// the blanket implementation in the standard library. [`From`] cannot do these type of
208
+ /// conversions because of Rust's orphaning rules.
207
209
///
208
- /// Library authors should not directly implement this trait, but should prefer
209
- /// implementing the [`From`][From] trait, which offers greater flexibility and
210
- /// provides an equivalent `Into` implementation for free, thanks to a blanket
211
- /// implementation in the standard library.
210
+ /// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`].
212
211
///
213
212
/// # Generic Implementations
214
213
///
215
- /// - [`From<T>`][From] ` for U` implies `Into<U> for T`
216
- /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
214
+ /// - [`From<T>`]` for U` implies `Into<U> for T`
215
+ /// - [`Into`]` is reflexive, which means that `Into<T> for T` is implemented
217
216
///
218
- /// # Implementing `Into`
217
+ /// # Implementing `Into` for conversions to external types
219
218
///
220
- /// There is one exception to implementing `Into`, and it's kind of esoteric.
221
- /// If the destination type is not part of the current crate, and it uses a
222
- /// generic variable, then you can't implement `From` directly. For example,
223
- /// take this crate:
219
+ /// If the destination type is not part of the current crate
220
+ /// then you can't implement [`From`] directly.
221
+ /// For example, take this code:
224
222
///
225
223
/// ```compile_fail
226
224
/// struct Wrapper<T>(Vec<T>);
@@ -230,8 +228,9 @@ pub trait AsMut<T: ?Sized> {
230
228
/// }
231
229
/// }
232
230
/// ```
233
- ///
234
- /// To fix this, you can implement `Into` directly:
231
+ /// This will fail to compile because we cannot implement a trait for a type
232
+ /// if both the trait and the type are not defined by the current crate.
233
+ /// This is due to Rust's orphaning rules. To bypass this, you can implement `Into` directly:
235
234
///
236
235
/// ```
237
236
/// struct Wrapper<T>(Vec<T>);
@@ -242,17 +241,22 @@ pub trait AsMut<T: ?Sized> {
242
241
/// }
243
242
/// ```
244
243
///
245
- /// This won't always allow the conversion: for example, `try!` and `?`
246
- /// always use `From`. However, in most cases, people use `Into` to do the
247
- /// conversions, and this will allow that .
244
+ /// It is important to understand that `Into` does not provide a [`From`] implementation
245
+ /// (as [ `From`] does with `Into`). Therefore, you should always try to implement [`From`]
246
+ /// and then fall back to `Into` if [`From`] can't be implemented .
248
247
///
249
- /// In almost all cases, you should try to implement `From`, then fall back
250
- /// to `Into` if `From ` can't be implemented .
248
+ /// Prefer using `Into` over [`From`] when specifying trait bounds on a generic function
249
+ /// to ensure that types that only implement `Into ` can be used as well .
251
250
///
252
251
/// # Examples
253
252
///
254
253
/// [`String`] implements `Into<Vec<u8>>`:
255
254
///
255
+ /// In order to express that we want a generic function to take all arguments that can be
256
+ /// converted to a specified type `T`, we can use a trait bound of `Into<T>`.
257
+ /// For example: The function `is_hello` takes all arguments that can be converted into a
258
+ /// `Vec<u8>`.
259
+ ///
256
260
/// ```
257
261
/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
258
262
/// let bytes = b"hello".to_vec();
@@ -276,44 +280,51 @@ pub trait Into<T>: Sized {
276
280
fn into ( self ) -> T ;
277
281
}
278
282
279
- /// Simple and safe type conversions in to `Self` . It is the reciprocal of
280
- /// `Into`.
283
+ /// Used to do value-to-value conversions while consuming the input value . It is the reciprocal of
284
+ /// [ `Into`] .
281
285
///
282
- /// This trait is useful when performing error handling as described by
283
- /// [the book][book] and is closely related to the `?` operator.
286
+ /// One should always prefer implementing [`From`] over [`Into`]
287
+ /// because implementing [`From`] automatically provides one with a implementation of [`Into`]
288
+ /// thanks to the blanket implementation in the standard library.
284
289
///
285
- /// When constructing a function that is capable of failing the return type
286
- /// will generally be of the form `Result<T, E>`.
290
+ /// Only implement [`Into`] if a conversion to a type outside the current crate is required.
291
+ /// [`From`] cannot do these type of conversions because of Rust's orphaning rules.
292
+ /// See [`Into`] for more details.
287
293
///
288
- /// The `From` trait allows for simplification of error handling by providing a
289
- /// means of returning a single error type that encapsulates numerous possible
290
- /// erroneous situations.
294
+ /// Prefer using [`Into`] over using [`From`] when specifying trait bounds on a generic function.
295
+ /// This way, types that directly implement [`Into`] can be used as arguments as well.
291
296
///
292
- /// This trait is not limited to error handling, rather the general case for
293
- /// this trait would be in any type conversions to have an explicit definition
294
- /// of how they are performed.
297
+ /// The [`From`] is also very useful when performing error handling. When constructing a function
298
+ /// that is capable of failing, the return type will generally be of the form `Result<T, E>`.
299
+ /// The `From` trait simplifies error handling by allowing a function to return a single error type
300
+ /// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more
301
+ /// details.
295
302
///
296
- /// **Note: this trait must not fail**. If the conversion can fail, use
297
- /// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
298
- /// [`Result<T, E>`].
303
+ /// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`].
299
304
///
300
305
/// # Generic Implementations
301
306
///
302
- /// - `From<T> for U` implies [`Into<U>`]` for T`
303
- /// - [`from `] is reflexive, which means that `From<T> for T` is implemented
307
+ /// - [ `From<T>`]` for U` implies [`Into<U>`]` for T`
308
+ /// - [`From `] is reflexive, which means that `From<T> for T` is implemented
304
309
///
305
310
/// # Examples
306
311
///
307
312
/// [`String`] implements `From<&str>`:
308
313
///
314
+ /// An explicit conversion from a &str to a String is done as follows:
309
315
/// ```
310
316
/// let string = "hello".to_string();
311
317
/// let other_string = String::from("hello");
312
318
///
313
319
/// assert_eq!(string, other_string);
314
320
/// ```
315
321
///
316
- /// An example usage for error handling:
322
+ /// While performing error handling it is often useful to implement `From` for your own error type.
323
+ /// By converting underlying error types to our own custom error type that encapsulates the
324
+ /// underlying error type, we can return a single error type without losing information on the
325
+ /// underlying cause. The '?' operator automatically converts the underlying error type to our
326
+ /// custom error type by calling `Into<CliError>::into` which is automatically provided when
327
+ /// implementing `From`. The compiler then infers which implementation of `Into` should be used.
317
328
///
318
329
/// ```
319
330
/// use std::fs;
0 commit comments