]> git.lizzy.rs Git - rust.git/commitdiff
FromStr implementation example
authorDonnie Bishop <donnie.a.bishop@gmail.com>
Sat, 25 Mar 2017 15:56:52 +0000 (11:56 -0400)
committerDonnie Bishop <donnie.a.bishop@gmail.com>
Sat, 25 Mar 2017 15:56:52 +0000 (11:56 -0400)
src/libcore/str/mod.rs

index dfb6936da6bda4d1f381aa9ef28dc208a3940850..bc5df6810a9d985fd429235fdcd344f65be38df9 100644 (file)
 /// [`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 = try!(coords[0].parse::<i32>());
+///         let y_fromstr = try!(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.