Skip to content

Commit 54bbe23

Browse files
author
Clar Charr
committed
Clarify docs on implementing Into.
1 parent a11c26f commit 54bbe23

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

src/libcore/convert.rs

+37-1
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,40 @@ pub trait AsMut<T: ?Sized> {
169169
/// - [`From<T>`][From]` for U` implies `Into<U> for T`
170170
/// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
171171
///
172+
/// # Implementing `Into`
173+
///
174+
/// There is one exception to implementing `Into`, and it's kind of esoteric.
175+
/// If the destination type is not part of the current crate, and it uses a
176+
/// generic variable, then you can't implement `From` directly. For example,
177+
/// take this crate:
178+
///
179+
/// ```compile_fail
180+
/// struct Wrapper<T>(Vec<T>);
181+
/// impl<T> From<Wrapper<T>> for Vec<T> {
182+
/// fn from(w: Wrapper<T>) -> Vec<T> {
183+
/// w.0
184+
/// }
185+
/// }
186+
/// ```
187+
///
188+
/// To fix this, you can implement `Into` directly:
189+
///
190+
/// ```
191+
/// struct Wrapper<T>(Vec<T>);
192+
/// impl<T> Into<Vec<T>> for Wrapper<T> {
193+
/// fn into(self) -> Vec<T> {
194+
/// self.0
195+
/// }
196+
/// }
197+
/// ```
198+
///
199+
/// This won't always allow the conversion: for example, `try!` and `?`
200+
/// always use `From`. However, in most cases, people use `Into` to do the
201+
/// conversions, and this will allow that.
202+
///
203+
/// In almost all cases, you should try to implement `From`, then fall back
204+
/// to `Into` if `From` can't be implemented.
205+
///
172206
/// # Examples
173207
///
174208
/// [`String`] implements `Into<Vec<u8>>`:
@@ -285,9 +319,11 @@ pub trait From<T>: Sized {
285319
/// Library authors should not directly implement this trait, but should prefer
286320
/// implementing the [`TryFrom`] trait, which offers greater flexibility and
287321
/// provides an equivalent `TryInto` implementation for free, thanks to a
288-
/// blanket implementation in the standard library.
322+
/// blanket implementation in the standard library. For more information on this,
323+
/// see the documentation for [`Into`].
289324
///
290325
/// [`TryFrom`]: trait.TryFrom.html
326+
/// [`Into`]: trait.Into.html
291327
#[unstable(feature = "try_from", issue = "33417")]
292328
pub trait TryInto<T>: Sized {
293329
/// The type returned in the event of a conversion error.

0 commit comments

Comments
 (0)