Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Traits can also be generic.

Here is a generic Convert trait that we will use to convert between numerical units. It declares a name() method that returns a conversion’s description and a convert() method that converts a T value into another T value:

We define two conversion structures that will implement the trait:

The first structure implements the trait for converting from degree Celsius to degree Fahrenheit:

The second structure converts from miles to kilometers:

In order to illustrate the polymorphism aspect of the trait, we define a function that prints the result of a conversion. It takes a Converter trait and a value to convert. The type T needs to be copyable and displayable, hence the double trait bound on Copy and Display:

We define one instance for each converter structure:

And call once the printing function for each converter, with a sample value:

Celsius to Fahrenheit: 100 -> 212
Miles to Kilometers: 5 -> 8.0467