Interfaces and Traits in C

https://news.ycombinator.com/rss Hits: 1
Summary

Interfaces and traits in CEveryone likes interfaces in Go and traits in Rust. Polymorphism without class-based hierarchies or inheritance seems to be the sweet spot. What if we try to implement this in C?Interfaces in Go • Traits in Rust • Toy example • Interface definition • Interface data • Method table • Method table in implementor • Type assertions • Final thoughtsInterfaces in GoAn interface in Go is a convenient way to define a contract for some useful behavior. Take, for example, the honored io.Reader:// Reader is the interface that wraps the basic Read method. type Reader interface { // Read reads up to len(p) bytes into p. It returns the number of bytes // read (0 <= n <= len(p)) and any error encountered. Read(p []byte) (n int, err error) } Anything that can read data into a byte slice provided by the caller is a Reader. Quite handy, because the code doesn't need to care where the data comes from — whether it's memory, the file system, or the network. All that matters is that it can read the data into a slice:// work processes the data read from r. func work(r io.Reader) int { buf := make([]byte, 8) n, err := r.Read(buf) if err != nil && err != io.EOF { panic(err) } // ... return n } We can provide any kind of reader:func main() { var total int b := bytes.NewBufferString("hello world") // bytes.Buffer implements io.Reader, so we can use it with work. total += work(b) total += work(b) fmt.Println("total =", total) } Go's interfaces are structural, which is similar to duck typing. A type doesn't need to explicitly state that it implements io.Reader; it just needs to have a Read method:// Zeros is an infinite stream of zero bytes. type Zeros struct{} func (z Zeros) Read(p []byte) (n int, err error) { clear(p) return len(p), nil } The Go compiler and runtime take care of the rest:func main() { var total int var z Zeros // Zeros implements io.Reader, so we can use it with work. total += work(z) total += work(z) fmt.Println("total =", total) } Traits in RustA tr...

First seen: 2026-01-22 16:44

Last seen: 2026-01-22 16:44