diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs index 85b648bbd59..1c1ad5fd33f 100644 --- a/src/libcore/convert.rs +++ b/src/libcore/convert.rs @@ -10,15 +10,35 @@ //! Traits for conversions between types. //! -//! The traits in this module provide a general way to talk about -//! conversions from one type to another. They follow the standard -//! Rust conventions of `as`/`to`/`into`/`from`. +//! The traits in this module provide a general way to talk about conversions from one type to +//! another. They follow the standard Rust conventions of `as`/`to`/`into`/`from`. +//! +//! Like many traits, these are often used as bounds for generic functions, to support arguments of +//! multiple types. +//! +//! See each trait for usage examples. #![stable(feature = "rust1", since = "1.0.0")] use marker::Sized; /// A cheap, reference-to-reference conversion. +/// +/// # Examples +/// +/// Both `String` and `&str` implement `AsRef`: +/// +/// ``` +/// fn is_hello>(s: T) { +/// assert_eq!("hello", s.as_ref()); +/// } +/// +/// let s = "hello"; +/// is_hello(s); +/// +/// let s = "hello".to_string(); +/// is_hello(s); +/// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait AsRef { /// Performs the conversion. @@ -34,8 +54,21 @@ pub trait AsMut { fn as_mut(&mut self) -> &mut T; } -/// A conversion that consumes `self`, which may or may not be -/// expensive. +/// A conversion that consumes `self`, which may or may not be expensive. +/// +/// # Examples +/// +/// `String` implements `Into>`: +/// +/// ``` +/// fn is_hello>>(s: T) { +/// let bytes = b"hello".to_vec(); +/// assert_eq!(bytes, s.into()); +/// } +/// +/// let s = "hello".to_string(); +/// is_hello(s); +/// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait Into: Sized { /// Performs the conversion. @@ -44,6 +77,19 @@ pub trait Into: Sized { } /// Construct `Self` via a conversion. +/// +/// # Examples +/// +/// `String` implements `From<&str>`: +/// +/// ``` +/// let s = "hello"; +/// let string = "hello".to_string(); +/// +/// let other_string: String = From::from(s); +/// +/// assert_eq!(string, other_string); +/// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait From { /// Performs the conversion.