Skip to content

Commit 710edc1

Browse files
committed
Add examples for Convert
1 parent 9f37ba6 commit 710edc1

File tree

1 file changed

+53
-5
lines changed

1 file changed

+53
-5
lines changed

src/libcore/convert.rs

+53-5
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,35 @@
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

1923
use 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")]
2343
pub 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")]
4073
pub trait Into<T>: Sized {
4174
/// Performs the conversion.
@@ -44,6 +77,21 @@ pub trait Into<T>: Sized {
4477
}
4578

4679
/// 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+
/// ```
4795
#[stable(feature = "rust1", since = "1.0.0")]
4896
pub trait From<T> {
4997
/// Performs the conversion.

0 commit comments

Comments
 (0)