Automatic From based on return type

Can From trait be processed on return value?

Example:

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

impl From<(i32, i32)> for Point {
    fn from(value: (i32, i32)) -> Point {
        Point {
            x: value.0,
            y: value.1,
        }
    }
}

fn calc_point() -> Point {
    (1, 2) // doesn't work
}

fn calc_point2<R: Into<Point>>() -> R {
    (1, 2) // doesn't work either 
}

fn main() {
    let p = calc_point();
}

Yes, you can call From::from.

fn calc_point() -> Point {
    From::from((1, 2))
}

I can. But it's not automatic. It's easier to write Point::new(1, 2) in this case.

In that case, no, there is no such feature in Rust. From::from is never called automatically.

1 Like

You can do (1,2).into() though.

Completely forgot about it. Thanks. It's already something.