1010
1111//! Traits for conversions between types.
1212//!
13- //! The traits in this module provide a general way to talk about
14- //! conversions from one type to another. They follow the standard
15- //! Rust conventions of `as`/`to`/`into`/`from`.
13+ //! The traits in this module provide a general way to talk about conversions from one type to
14+ //! another. They follow the standard Rust conventions of `as`/`to`/`into`/`from`.
15+ //!
16+ //! Like many traits, these are often used as bounds for generic functions, to support arguments of
17+ //! multiple types.
18+ //!
19+ //! See each trait for usage examples.
1620
1721#![ stable( feature = "rust1" , since = "1.0.0" ) ]
1822
1923use marker:: Sized ;
2024
2125/// A cheap, reference-to-reference conversion.
26+ ///
27+ /// # Examples
28+ ///
29+ /// Both `String` and `&str` implement `AsRef<str>`:
30+ ///
31+ /// ```
32+ /// fn is_hello<T: AsRef<str>>(s: T) {
33+ /// assert_eq!("hello", s.as_ref());
34+ /// }
35+ ///
36+ /// let s = "hello";
37+ /// is_hello(s);
38+ ///
39+ /// let s = "hello".to_string();
40+ /// is_hello(s);
41+ /// ```
2242#[ stable( feature = "rust1" , since = "1.0.0" ) ]
2343pub trait AsRef < T : ?Sized > {
2444 /// Performs the conversion.
@@ -34,8 +54,21 @@ pub trait AsMut<T: ?Sized> {
3454 fn as_mut ( & mut self ) -> & mut T ;
3555}
3656
37- /// A conversion that consumes `self`, which may or may not be
38- /// expensive.
57+ /// A conversion that consumes `self`, which may or may not be expensive.
58+ ///
59+ /// # Examples
60+ ///
61+ /// `String` implements `Into<Vec<u8>>`:
62+ ///
63+ /// ```
64+ /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
65+ /// let bytes = b"hello".to_vec();
66+ /// assert_eq!(bytes, s.into());
67+ /// }
68+ ///
69+ /// let s = "hello".to_string();
70+ /// is_hello(s);
71+ /// ```
3972#[ stable( feature = "rust1" , since = "1.0.0" ) ]
4073pub trait Into < T > : Sized {
4174 /// Performs the conversion.
@@ -44,6 +77,19 @@ pub trait Into<T>: Sized {
4477}
4578
4679/// Construct `Self` via a conversion.
80+ ///
81+ /// # Examples
82+ ///
83+ /// `String` implements `From<&str>`:
84+ ///
85+ /// ```
86+ /// let s = "hello";
87+ /// let string = "hello".to_string();
88+ ///
89+ /// let other_string: String = From::from(s);
90+ ///
91+ /// assert_eq!(string, other_string);
92+ /// ```
4793#[ stable( feature = "rust1" , since = "1.0.0" ) ]
4894pub trait From < T > {
4995 /// Performs the conversion.
0 commit comments