11//! Traits for conversions between types.
22//!
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:
65//!
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.
913//!
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.
1516//!
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
1718//! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
1819//! as [`From`] and [`TryFrom`] provide greater flexibility and offer
1920//! 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.
2423//!
2524//! # Generic Implementations
2625//!
@@ -99,28 +98,22 @@ use fmt;
9998#[ inline]
10099pub const fn identity < T > ( x : T ) -> T { x }
101100
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.
104102///
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.
107106///
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.
114107///
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`] :
116109///
117110/// - Use `AsRef` when the goal is to simply convert into a reference
118111/// - Use `Borrow` when the goal is related to writing code that is agnostic to
119112/// the type of borrow and whether it is a reference or value
120113///
121114/// [`Borrow`]: ../../std/borrow/trait.Borrow.html
122115///
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
124117/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
125118///
126119/// [`Option<T>`]: ../../std/option/enum.Option.html
@@ -134,7 +127,12 @@ pub const fn identity<T>(x: T) -> T { x }
134127///
135128/// # Examples
136129///
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.
138136///
139137/// [`String`]: ../../std/string/struct.String.html
140138///
@@ -157,12 +155,13 @@ pub trait AsRef<T: ?Sized> {
157155 fn as_ref ( & self ) -> & T ;
158156}
159157
160- /// A cheap, mutable reference -to-mutable reference conversion.
158+ /// Used to do a cheap mutable-to-mutable reference conversion.
161159///
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.
164163///
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
166165/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
167166///
168167/// [`Option<T>`]: ../../std/option/enum.Option.html
@@ -176,10 +175,11 @@ pub trait AsRef<T: ?Sized> {
176175///
177176/// # Examples
178177///
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:
183183/// ```
184184/// fn add_one<T: AsMut<u64>>(num: &mut T) {
185185/// *num.as_mut() += 1;
@@ -189,7 +189,7 @@ pub trait AsRef<T: ?Sized> {
189189/// add_one(&mut boxed_num);
190190/// assert_eq!(*boxed_num, 1);
191191/// ```
192- ///
192+ /// [`Box<T>`]: ../../std/boxed/struct.Box.html
193193///
194194#[ stable( feature = "rust1" , since = "1.0.0" ) ]
195195pub trait AsMut < T : ?Sized > {
@@ -198,29 +198,27 @@ pub trait AsMut<T: ?Sized> {
198198 fn as_mut ( & mut self ) -> & mut T ;
199199}
200200
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`].
203203///
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.
207209///
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`].
212211///
213212/// # Generic Implementations
214213///
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
217216///
218- /// # Implementing `Into`
217+ /// # Implementing `Into` for conversions to external types
219218///
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:
224222///
225223/// ```compile_fail
226224/// struct Wrapper<T>(Vec<T>);
@@ -230,8 +228,9 @@ pub trait AsMut<T: ?Sized> {
230228/// }
231229/// }
232230/// ```
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:
235234///
236235/// ```
237236/// struct Wrapper<T>(Vec<T>);
@@ -242,17 +241,22 @@ pub trait AsMut<T: ?Sized> {
242241/// }
243242/// ```
244243///
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 .
248247///
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 .
251250///
252251/// # Examples
253252///
254253/// [`String`] implements `Into<Vec<u8>>`:
255254///
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+ ///
256260/// ```
257261/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
258262/// let bytes = b"hello".to_vec();
@@ -276,44 +280,51 @@ pub trait Into<T>: Sized {
276280 fn into ( self ) -> T ;
277281}
278282
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`] .
281285///
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.
284289///
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.
287293///
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.
291296///
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.
295302///
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`].
299304///
300305/// # Generic Implementations
301306///
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
304309///
305310/// # Examples
306311///
307312/// [`String`] implements `From<&str>`:
308313///
314+ /// An explicit conversion from a &str to a String is done as follows:
309315/// ```
310316/// let string = "hello".to_string();
311317/// let other_string = String::from("hello");
312318///
313319/// assert_eq!(string, other_string);
314320/// ```
315321///
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.
317328///
318329/// ```
319330/// use std::fs;
0 commit comments