Automatic From based on return type


#1

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();
}

#2

Yes, you can call From::from.

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

#3

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


#4

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


#5

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


#6

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