Reputation: 381
I have the following struct
struct Position<T> {
ns: i32,
we: i32,
orientation: T
}
I'd like to have the following method without having to repeat its implementation for each and every type T I intend to use, since the method implementation does not actually depend on T I would think this is possible to do but I can't figure out how.
impl Position {
fn distance(&self) -> i32 {
self.ns.abs() + self.we.abs()
}
}
I have tried adding a type parameter to the impl line but apparently that only works for a concrete type not for a type variable which is what I would need here to do what I want I think. I have tried something along the lines of <_>
but no dice either.
Is this possible to do in Rust?
Upvotes: 0
Views: 203
Reputation: 42592
T
is an intrinsic part of Position
, so you need to impl Position<T>
, but then T doesn't exist in the scope of the impl
block (there is no intrinsic relationship between the struct
and impl
blocks, indeed they could use completely different parameter names), so you need to declare it:
impl<T> Position<T> {
fn distance(&self) -> i32 {
self.ns.abs() + self.we.abs()
}
}
Upvotes: 2
Reputation: 16535
If you have methods on Position
has apply to any T
, you can place them in a impl
that has no bounds:
impl<T> Position<T> {
fn distance(&self) -> i32 {
self.ns.abs() + self.we.abs()
}
// fn ....
}
Remember that you can have multiple impl
blocks for a type. So if you have methods that require T
to be bound, you can add
impl<T: Clone> Position<T> {
// fn ...
}
Upvotes: 2