How to Use the From and Into Traits for Type Conversion

Use From for defining infallible type conversions and Into for automatic conversion calls in Rust.

Use From for infallible conversions where the source type knows how to create the target, and Into for fallible or flexible conversions where the target type defines the logic. Implement From for the source type to automatically get Into for the target.

use std::convert::{From, Into};

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

impl From<(i32, i32)> for Point {
    fn from((x, y): (i32, i32)) -> Self {
        Point { x, y }
    }
}

fn main() {
    let p: Point = (1, 2).into(); // Uses From automatically
    println!("{:?}", p);
}