Implement the From trait on the source struct to define the conversion logic, then use the .into() method on the source instance to convert it to the target type. This approach leverages Rust's standard conversion traits to handle type casting cleanly without manual field-by-field copying.
struct Point {
x: i32,
y: i32,
}
struct Point2D {
x: i32,
y: i32,
}
impl From<Point> for Point2D {
fn from(point: Point) -> Self {
Point2D { x: point.x, y: point.y }
}
}
fn main() {
let p = Point { x: 10, y: 20 };
let p2d: Point2D = p.into();
}