Understanding the From and To traits

I created this repo to help me understand using the From and Into traits: GitHub - mvolkmann/rust-from-into

Parts of it work fine, but I haven't been able to determine the correct way to call the into method here:

The error is "mismatched types
expected struct Point3D
found reference &_rustcE0308" but it's not clear to me how to fix this. It seems like I only want to call into on references because I don't want this to transfer ownership.

Does let p3 = p2.into() work? That should be equivlent to let p3 = (&p2).into() due to an auto ref for receivers.

When I try let p3 = p2.into(); it says "error: type annotations needed". It wants me to specify the type of p3. But when I try let p3: Point3D = p2.into(); it says "error: the trait bound Point3D: From<Point2D> is not satisfied. My code implements the From trait for &Point2D, but not Point2D. It seems like I only want to implement it for &Point2D though.

Method calls (dot operator) have higher precedence than references (& operator).

Just put parentheses around your references:

(&p2).into()

The built-in precedence rules means you are effectively doing this:

&(p2.into())

which makes the compiler error make sense.

1 Like