DEV Community

BC
BC

Posted on

Day4:From & Display & FromStr traits - 100DayOfRust

1, From trait

After you defined the From trait, you can convert a type A to B by calling B::from(A) or B = A.into()

use std::convert::From;

#[derive(Debug)]
struct Number {
    num: i32
}

impl From<i32> for Number {
    fn from(item: i32) -> Self {
        Number {num: item}
    }
}

fn main() {
    let i = 5;
    let num1 = Number::from(i);
    let num2: Number = i.into();
    println!("num1: {:?}, num2: {:?}", num1, num2);
}
Enter fullscreen mode Exit fullscreen mode

Result:

num1: 5, num2: 5
Enter fullscreen mode Exit fullscreen mode

2, Display & FromStr trait

The Display trait will be used when print an object, e.g. obj.to_string() or println!("{}", obj);
The FromStr will be used when trying to convert a string to the target object with parse() method

use std::fmt;
use std::str::FromStr;
use std::num::ParseIntError;

struct Point {
    x: i32,
    y: i32,
}

impl fmt::Display for Point {
    fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result {
        write!(f, "Point ({}, {})", self.x, self.y)
    }
}

impl FromStr for Point {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let tuple: Vec<&str> = s.split(",").collect();
        let x = tuple[0].parse::<i32>()?;
        let y = tuple[1].parse::<i32>()?;
        Ok(Point {x:x, y:y})
    }
}

fn main() {
    let p1 = Point {x:1, y:2};
    let p2: Point = "3,4".parse().unwrap();
    println!("P1: {}\nP2: {}", p1, p2);
}
Enter fullscreen mode Exit fullscreen mode

Result:

P1: Point (1, 2)
P2: Point (3, 4)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)