Imitating Rust’s trait system in JavaScript

Generics and traits are great for DRY code. They let you get by with writing code once that works (almost) everywhere. Unfortunately, Rust doesn’t have built-in support for implementing the same trait for different concrete structs. As a work-around, Rust developers have come up with solutions like macros to avoid repetition.

Traits in Rust

Here’s a simple example of how Rust deals with traits:

What happened there? I created 2 structs Foo and Bar, and for each of them I implemented a function X() that would print their a field. This works because both Foo and Bar have a field a. After, I also implemented a function Y() that would print the b field of Bar since only Bar has a field named b. If I tried the same macro trick to implement Y() for Foo, the compiler would yell at me that Foo doesn’t have a field b.

Let’s see how to do this in JavaScript

What happened here? Functions in JavaScript are passed a context argument when they’re being called. It’s automatically assigned when invoking functions as X() or Y(), but if you invoke them with .call() you can specify your own context. The context is available as this inside your function. This allows us to model a struct in Rust as a typical JavaScript object. Then implementing a function for a struct is simply passing in our JavaScript object as the context to the function.

Pros and Cons

Ultimately, it all boils down to safety vs. flexibility. Rust guarantees at compile time the struct supports the function being implemented. Using the earlier example, implementing Y() for Foo is impossible because Foo doesn’t contain the field b. In JavaScript this is totally possible,; would simply result in a is 1 \n b is undefined. On the other hand, JavaScript doesn’t require a “solution” like a macro to implement the same function for multiple structs.

In a future post I will also expand on the similarities of function overriding between Rust and JavaScript.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.