10
10
11
11
//! Traits for conversions between types.
12
12
//!
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.
16
20
17
21
#![ stable( feature = "rust1" , since = "1.0.0" ) ]
18
22
19
23
use marker:: Sized ;
20
24
21
25
/// 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
+ /// ```
22
42
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
23
43
pub trait AsRef < T : ?Sized > {
24
44
/// Performs the conversion.
@@ -34,8 +54,21 @@ pub trait AsMut<T: ?Sized> {
34
54
fn as_mut ( & mut self ) -> & mut T ;
35
55
}
36
56
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
+ /// ```
39
72
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
40
73
pub trait Into < T > : Sized {
41
74
/// Performs the conversion.
@@ -44,6 +77,21 @@ pub trait Into<T>: Sized {
44
77
}
45
78
46
79
/// Construct `Self` via a conversion.
80
+ ///
81
+ /// # Examples
82
+ ///
83
+ /// `Vec<u8>` implements `From<String>`:
84
+ ///
85
+ /// ```
86
+ /// fn is_hello<T: From<String>>(v: T) {
87
+ /// let string = "hello".to_string();
88
+ ///
89
+ /// assert_eq!(string, v.from());
90
+ /// }
91
+ ///
92
+ /// let b = b"hello".to_vec();
93
+ /// is_hello(b);
94
+ /// ```
47
95
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
48
96
pub trait From < T > {
49
97
/// Performs the conversion.
0 commit comments