Reputation:
I'd like to know how to call a function from a trait providing that there are several traits with the same function names.
The problem is in the 33 line or
tr1::tr(v);
How I have to express which trait I want to call?
struct V2D {
x: i32,
y: i32
}
impl V2D {
fn new(x: i32, y: i32) -> V2D {
V2D { x, y }
}
}
trait tr1 {
fn tr();
}
trait tr2 {
fn tr();
}
impl tr1 for V2D {
fn tr() {
println!("This is tr1");
}
}
impl tr2 for V2D {
fn tr() {
println!("This is tr2");
}
}
fn main() {
let v = V2D::new(1,2);
tr1::tr(v);
}
Upvotes: 2
Views: 968
Reputation: 4461
The simplest way would be using fully qualified syntax. In your case tr
is an associated function so all you need is a little typecasting:
fn main() {
let v = V2D::new(1,2);
<V2D as tr1>::tr();
<V2D as tr2>::tr();
}
The syntax for methods on the other hand would be something like this:
struct V2D {
x: i32,
y: i32
}
impl V2D {
fn new(x: i32, y: i32) -> V2D {
V2D{x,y}
}
}
trait tr1 {
fn tr(&self);
}
trait tr2 {
fn tr(&self);
}
impl tr1 for V2D {
fn tr(&self) {
println!("This is tr1");
}
}
impl tr2 for V2D {
fn tr(&self) {
println!("This is tr2");
}
}
fn main() {
let v = V2D::new(1,2);
tr1::tr(&v);
}
Upvotes: 1
Reputation: 30001
The syntax you have used (tr1::tr(v)
) would be correct if your method took has a self
parameter (Permalink to the playground), but if it doesn't, you need to call it on the type specifying the type and trait explicitly:
<V2D as tr1>::tr()
Upvotes: 2