Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an example of implementing the FromStr trait for Circles. #1865

Merged
merged 1 commit into from
Jul 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions src/conversion/string.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ shown in the following example.

This will convert the string into the type specified as long as the [`FromStr`]
trait is implemented for that type. This is implemented for numerous types
within the standard library. To obtain this functionality on a user defined type
simply implement the [`FromStr`] trait for that type.
within the standard library.

```rust,editable
fn main() {
Expand All @@ -49,6 +48,35 @@ fn main() {
}
```

To obtain this functionality on a user defined type simply implement the
[`FromStr`] trait for that type.

```rust,editable
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug)]
struct Circle {
radius: i32,
}
impl FromStr for Circle {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().parse() {
Ok(num) => Ok(Circle{ radius: num }),
Err(e) => Err(e),
}
}
}
fn main() {
let radius = " 3 ";
let circle: Circle = radius.parse().unwrap();
println!("{:?}", circle);
}
```

[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html
[Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html
[print]: ../hello/print.md
Expand Down
Loading