Universal function call syntax

There are times when you are using a type that has the same set of methods as one of its implemented traits. In those situations, Rust provides us with the uniform function call syntax that works for calling methods that are either on types themselves or come from a trait. Consider the following code:

// ufcs.rs

trait Driver {
fn drive(&self) {
println!("Driver's driving!");
}
}

struct MyCar;

impl MyCar {
fn drive(&self) {
println!("I'm driving!");
}
}

impl Driver for MyCar {}

fn main() {
let car = MyCar;
car.drive();
}

The preceding code has two methods with the same name, drive. One of them is an inherent method and the other comes from the trait, Driver. If we compile and run this, we get the following output:

I'm driving

Well, what if we wanted to call the Driver trait's drive method? Inherent methods on types are given higher priority than other methods with the same name. To call a trait method, we can use the Universal Function Call Syntax (UFCS).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset