rust-by-practice/solutions/type-conversions/others.md

76 lines
1.5 KiB
Markdown
Raw Permalink Normal View History

2022-03-10 00:24:28 -06:00
1
2022-05-01 00:08:50 -05:00
2022-03-10 00:24:28 -06:00
```rust
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "The point is ({}, {})", self.x, self.y)
}
}
fn main() {
let origin = Point { x: 0, y: 0 };
assert_eq!(origin.to_string(), "The point is (0, 0)");
assert_eq!(format!("{}", origin), "The point is (0, 0)");
println!("Success!")
}
```
2.
2022-05-01 00:08:50 -05:00
2022-03-10 00:24:28 -06:00
```rust
// To use `from_str` method, you needs to introduce this trait into the current scope.
use std::str::FromStr;
fn main() {
let parsed: i32 = "5".parse().unwrap();
let turbo_parsed = "10".parse::<i32>().unwrap();
let from_str = i32::from_str("20").unwrap();
let sum = parsed + turbo_parsed + from_str;
assert_eq!(sum, 35);
println!("Success!")
}
```
3.
2022-05-01 00:08:50 -05:00
2022-03-10 00:24:28 -06:00
```rust
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 })
}
}
fn main() {
let p = "(3,4)".parse::<Point>();
assert_eq!(p.unwrap(), Point{ x: 3, y: 4} )
}
```
```rust
let p = Point::from_str("(3,4)");
```