about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorAlex Crichton <alex@alexcrichton.com>2017-03-27 15:24:23 -0500
committerAlex Crichton <alex@alexcrichton.com>2017-03-27 15:56:25 -0700
commit6b2c4bf22b68fbb4a546d0eaffe487cdfe240391 (patch)
treea8450f3657a2fad789322d18229e6ec5a6f81497 /src/libcore
parent84712faaa50c8bdefbffccd896f4088d17fbb4f9 (diff)
parentfb5e63fc475996ee5c65fb1b8686b8db17eb1e63 (diff)
downloadrust-6b2c4bf22b68fbb4a546d0eaffe487cdfe240391.tar.gz
rust-6b2c4bf22b68fbb4a546d0eaffe487cdfe240391.zip
Rollup merge of #40824 - donniebishop:fromstr_docexample, r=steveklabnik
FromStr implementation example

Referencing #29375. Added example implementation of FromStr trait to API Documentation
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/str/mod.rs33
1 files changed, 33 insertions, 0 deletions
diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs
index 2ef0eb0cdcf..0d66d0e93aa 100644
--- a/src/libcore/str/mod.rs
+++ b/src/libcore/str/mod.rs
@@ -35,6 +35,39 @@ pub mod pattern;
 /// [`from_str`]: #tymethod.from_str
 /// [`str`]: ../../std/primitive.str.html
 /// [`parse`]: ../../std/primitive.str.html#method.parse
+///
+/// # Examples
+///
+/// Basic implementation of `FromStr` on an example `Point` type:
+///
+/// ```
+/// use std::str::FromStr;
+/// use std::num::ParseIntError;
+///
+/// #[derive(Debug, PartialEq)]
+/// struct Point {
+///     x: i32,
+///     y: i32
+/// }
+///
+/// impl FromStr for Point {
+///     type Err = ParseIntError;
+///
+///     fn from_str(s: &str) -> Result<Self, Self::Err> {
+///         let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
+///                                  .split(",")
+///                                  .collect();
+///
+///         let x_fromstr = coords[0].parse::<i32>()?;
+///         let y_fromstr = coords[1].parse::<i32>()?;
+///
+///         Ok(Point { x: x_fromstr, y: y_fromstr })
+///     }
+/// }
+///
+/// let p = Point::from_str("(1,2)");
+/// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
+/// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 pub trait FromStr: Sized {
     /// The associated error which can be returned from parsing.