Do we have a "UFCS" in Rust?

D language, as well as Nim, both of which are nowhere near as popular as Rust, both have quite a useful feature, baked in directly in the language: Uniform Function Call Syntax (UFCS).

Do we have any alternative to it in Rust?

If not, what would it take to create it?

No, while we have something with that name, it is exactly the opposite. Allowing methods to be called as if they are associated functions. Eg Foo::bar(baz) instead of baz.bar(). To get what D calls "UFCS" you would need to write a macro. This will mean that methods are unavailable though as a macro can't know if something is a method or a free function. As alternative extension traits are often used. For example:

trait VecExt {
    fn multiply_all_elements_by(&mut self, amount: u64);
}

impl VecExt for Vec<u64> {
    fn multiply_all_elements_by(&mut self, amount: u64) {
        for i in self.iter_mut() {
            *i *= amount;
        }
    }
}

let mut v = vec![1u64];
v.multiply_all_elements_by(42);

In my opinion UFCS would be much less useful in Rust than it is in D:

  • In D it is not possible to add methods to an existing class, in Rust this is already possible with traits.
  • Templates in D work on the syntax level, unlike generics in Rust. This means that in D, UFCS functions can be used instead of methods in templates instantiations, while in Rust you need a trait anyway to write generics.

In short, Rust already has other (IMO better) ways to achieve the same. Rust uses traits on a semantic level, while UFCS is purely syntactic.

2 Likes