Polymorphism through interfaces (Go) and traits (Rust) can be implemented in C using structs and function pointers. The article walks through multiple approaches, starting with naive implementations that have memory overhead and layout dependencies, then evolving to a method table pattern that stores interface methods separately from data. The final solution uses a static method table referenced by the interface struct, achieving memory efficiency (16 bytes per interface instance) while maintaining type safety and supporting multiple interface implementations. Includes working code examples and comparisons to Go's io.Reader and Rust's std::io::Read.

15m read timeFrom antonz.org
Post cover image
Table of contents
Interfaces in GoTraits in RustToy exampleInterface definitionInterface dataMethod tableAlternative: Method table in implementorBonus: Type assertionsFinal thoughts
1 Comment

Sort: