On Chapter 10-1 of the book the following code is used:
struct Point<T, U> {
x: T,
y: U,
}
impl<T, U> Point<T, U> {
fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
Point {
x: self.x,
y: other.y,
}
}
}
fn main() {
let p1 = Point { x: 5, y: 10.4 };
let p2 = Point { x: "Hello", y: 'c' };
let p3 = p1.mixup(p2);
println!("p3.x = {}, p3.y = {}", p3.x, p3.y);
}
I notice that the mixup()
definition uses self
and other
(without references) so I expected that once the method is called, it takes ownership of the data of both p1
and p2
and once it finished executing this objects would be gone. This was in fact the case, The compiler doesn't allow me to use p1
or p2
after calling let p3 = p1.mixup(p2);
.
My question is, how would one rewrite the method definition so that it doesn't eat p1
and p2
? I tried the following:
impl<T, U> Point<T, U> {
fn mixup<V, W>(&self, other: &Point<V, W>) -> Point<T, W> {
Point {
x: *self.x,
y: *other_point.y,
}
}
}
My logic is that I use references for self
and other
and then I dereference the attributes (to get the data store in the attributes) when building the new Point
. However I got the following errors:
type `T` cannot be dereferenced
type `W` cannot be dereferenced