tezvyn:

Static dispatch over Write with generics in Rust

Source: interviewintermediate

WHAT IT TESTS: static vs dynamic dispatch trade-offs. OUTLINE: write generically over the std::io::Write trait with a type parameter W: Write, letting the compiler monomorphize and inline per concrete type, avoiding the vtable indirection of Box<dyn Write>.

WHAT IT TESTS: choosing static dispatch via generics over dynamic dispatch via trait objects. ANSWER OUTLINE: abstract over the std::io::Write trait. Make your component generic, struct Writer<W: Write> or fn emit<W: Write>(w: &mut W), so each concrete destination, stdout, File, TcpStream, instantiates a specialized version through monomorphization. The compiler can inline and optimize, eliminating the vtable lookup that Box<dyn Write> incurs. Trade-off is code bloat and loss of runtime heterogeneity.

Read the original → interview

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

Static dispatch over Write with generics in Rust · Tezvyn