1- //! Traits for conversions between types.
21//!
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.
63//!
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:
95//!
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.
1512//!
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
1717//! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
1818//! as [`From`] and [`TryFrom`] provide greater flexibility and offer
1919//! 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.
2422//!
2523//! # Generic Implementations
2624//!
@@ -99,28 +97,20 @@ use fmt;
9997#[ inline]
10098pub const fn identity < T > ( x : T ) -> T { x }
10199
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.
107104///
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:
116105///
106+ /// `AsRef` is very similar to, but serves a slightly different purpose than [`Borrow`]:
117107/// - Use `AsRef` when the goal is to simply convert into a reference
118108/// - Use `Borrow` when the goal is related to writing code that is agnostic to
119109/// the type of borrow and whether it is a reference or value
120110///
121111/// [`Borrow`]: ../../std/borrow/trait.Borrow.html
122112///
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
124114/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
125115///
126116/// [`Option<T>`]: ../../std/option/enum.Option.html
@@ -134,7 +124,11 @@ pub const fn identity<T>(x: T) -> T { x }
134124///
135125/// # Examples
136126///
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.
138132///
139133/// [`String`]: ../../std/string/struct.String.html
140134///
@@ -157,12 +151,12 @@ pub trait AsRef<T: ?Sized> {
157151 fn as_ref ( & self ) -> & T ;
158152}
159153
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 .
164158///
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
166160/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
167161///
168162/// [`Option<T>`]: ../../std/option/enum.Option.html
@@ -176,10 +170,11 @@ pub trait AsRef<T: ?Sized> {
176170///
177171/// # Examples
178172///
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:
183178/// ```
184179/// fn add_one<T: AsMut<u64>>(num: &mut T) {
185180/// *num.as_mut() += 1;
@@ -189,7 +184,7 @@ pub trait AsRef<T: ?Sized> {
189184/// add_one(&mut boxed_num);
190185/// assert_eq!(*boxed_num, 1);
191186/// ```
192- ///
187+ /// [`Box<T>`]: ../../std/boxed/struct.Box.html
193188///
194189#[ stable( feature = "rust1" , since = "1.0.0" ) ]
195190pub trait AsMut < T : ?Sized > {
@@ -198,29 +193,24 @@ pub trait AsMut<T: ?Sized> {
198193 fn as_mut ( & mut self ) -> & mut T ;
199194}
200195
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`].
203198///
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.
207203///
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`].
212205///
213206/// # Generic Implementations
214207///
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
219210///
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:
224214///
225215/// ```compile_fail
226216/// struct Wrapper<T>(Vec<T>);
@@ -230,8 +220,9 @@ pub trait AsMut<T: ?Sized> {
230220/// }
231221/// }
232222/// ```
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:
235226///
236227/// ```
237228/// struct Wrapper<T>(Vec<T>);
@@ -242,17 +233,21 @@ pub trait AsMut<T: ?Sized> {
242233/// }
243234/// ```
244235///
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.
248240///
249- /// In almost all cases, you should try to implement `From`, then fall back
250- /// to `Into` if `From` can't be implemented.
251241///
252242/// # Examples
253243///
254244/// [`String`] implements `Into<Vec<u8>>`:
255245///
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+ ///
256251/// ```
257252/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
258253/// let bytes = b"hello".to_vec();
@@ -276,44 +271,49 @@ pub trait Into<T>: Sized {
276271 fn into ( self ) -> T ;
277272}
278273
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`] .
281276///
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.
284282///
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.
291285///
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.
295291///
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`].
299293///
300294/// # Generic Implementations
301295///
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
304298///
305299/// # Examples
306300///
307301/// [`String`] implements `From<&str>`:
308302///
303+ /// An explicit conversion from a &str to a String is done as follows:
309304/// ```
310305/// let string = "hello".to_string();
311306/// let other_string = String::from("hello");
312307///
313308/// assert_eq!(string, other_string);
314309/// ```
315310///
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.
317317///
318318/// ```
319319/// use std::fs;
@@ -350,7 +350,7 @@ pub trait Into<T>: Sized {
350350/// [`String`]: ../../std/string/struct.String.html
351351/// [`Into<U>`]: trait.Into.html
352352/// [`from`]: trait.From.html#tymethod.from
353- /// [book]: ../../book/ch09-00- error-handling.html
353+ /// [book]: ../../book/first-edition/ error-handling.html
354354#[ stable( feature = "rust1" , since = "1.0.0" ) ]
355355pub trait From < T > : Sized {
356356 /// Performs the conversion.
0 commit comments