A Trait worse than death

Going back many a year before C++ was in general circulation I had occasion to write a graphics library. It would need to be able to use a couple of different screen based APIs and also assorted pen plotters.

To this end the individual drivers populated a virtual function table that would be called by the API layer. In effect a manual implementation of a C++ class system with "virtual" methods.

The need for languages to have these sorts of mechanisms is clear. Of late languages have broken away from C++ classes.

Golang has instead the idea of an interface, the definition of an interface specifies what functions (no variables) that interface has. At that point any struct that contains all those functions can call a function that wants the interface as a parameter. It's a great concept, very flexible, a struct might satisfy any number of different interfaces without the need for inheritance.

Rust decides to change the game again and has traits which are like interfaces but with a couple of key differences.

  1. Rust allows you to specify default implementations of functions. We see that in the Iterator trait, there are a score of iterator functions, but to implement our own iterator we only have to implement the "next" trait. In golang you can create your own base struct with the needed functions and embed it in your own struct to provide an inheritance of the functions to much the same effect.
  2. Golang just cares about you having the right functions and so your struct can satisfy interfaces without even knowing about it! Rust requires us to implement the traits individually for each trait a struct needs to work with. 

Is there a better of worse there? I'm coming out in favour of Rust, despite Golang being a language I love a lot. The Rust approach seems cleaner and less accident prone.

What is missing from the above in golang is inheritance, golang doesn't do inheritance off the bat, but it can be achieved nonetheless (article coming soon)

Rust looks more problematic in this area, I stand to be corrected but I think a few tricks could be learned from golang.

This page should end with a traits example, but it won't as I prefer more real world meaty code and noddy examples of traits are ten a penny.

Instead we will use traits to illustrate error handling

 

 


Comments

Popular posts from this blog

A reliable tuya authentication in node-red

node-red a full home automation example

Arduino boards - what I wish I'd known when starting