Using generic trait methods like .into() when type inference is impossible

You could use From::from:

use std::convert::*;

struct NewType(pub i32);

impl From<NewType> for i32 {
    fn from(src: NewType) -> i32 {
        src.0
    }
}

fn main() {
    let a = NewType(5);
    println!("{}", i32::from(a));
}

You can read more about it in the docs for the convert module.

Leave a Comment