Skip to content

Commit 6b2c4bf

Browse files
committed
Rollup merge of rust-lang#40824 - donniebishop:fromstr_docexample, r=steveklabnik
FromStr implementation example Referencing rust-lang#29375. Added example implementation of FromStr trait to API Documentation
2 parents 84712fa + fb5e63f commit 6b2c4bf

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/libcore/str/mod.rs

+33
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,39 @@ pub mod pattern;
3535
/// [`from_str`]: #tymethod.from_str
3636
/// [`str`]: ../../std/primitive.str.html
3737
/// [`parse`]: ../../std/primitive.str.html#method.parse
38+
///
39+
/// # Examples
40+
///
41+
/// Basic implementation of `FromStr` on an example `Point` type:
42+
///
43+
/// ```
44+
/// use std::str::FromStr;
45+
/// use std::num::ParseIntError;
46+
///
47+
/// #[derive(Debug, PartialEq)]
48+
/// struct Point {
49+
/// x: i32,
50+
/// y: i32
51+
/// }
52+
///
53+
/// impl FromStr for Point {
54+
/// type Err = ParseIntError;
55+
///
56+
/// fn from_str(s: &str) -> Result<Self, Self::Err> {
57+
/// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
58+
/// .split(",")
59+
/// .collect();
60+
///
61+
/// let x_fromstr = coords[0].parse::<i32>()?;
62+
/// let y_fromstr = coords[1].parse::<i32>()?;
63+
///
64+
/// Ok(Point { x: x_fromstr, y: y_fromstr })
65+
/// }
66+
/// }
67+
///
68+
/// let p = Point::from_str("(1,2)");
69+
/// assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
70+
/// ```
3871
#[stable(feature = "rust1", since = "1.0.0")]
3972
pub trait FromStr: Sized {
4073
/// The associated error which can be returned from parsing.

0 commit comments

Comments
 (0)