Skip to content

Instantly share code, notes, and snippets.

View revoltez's full-sized avatar
🏠
Working from home

Houadef Salih revoltez

🏠
Working from home
View GitHub Profile
@revoltez
revoltez / Associated Types.md
Created October 25, 2022 15:05 — forked from DarinM223/Associated Types.md
Associated types

Introduction to associated types

One of the most useful things in typed programming languages is generics. Generics allows you to write code that works across multiple types while still being checkable by the compiler. Even better is that with many languages like Rust and C#, generics have a distinct performance advantage over runtime casting. However although generics are extremely useful, many programming languages that have them don't allow for convenient ways of expressing them, especially for traits/interfaces. Like in Java if you want a generic interface you are forced to use the same Name<Type1, Type2, Type3, ...> syntax that you would use for a class. However, that often leads to ugly overly-verbose code.

Here's an example: Lets say that you have two traits/interfaces Foo and Bar that depend on three subtypes and you wanted a function that takes in any implementation of both Foo and Bar and returns the first type of Foo and the third type of Bar. The traditional Rust version that is similar to o