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