
The Visitor Pattern in Rust With Traits and Enums Compared
In languages without sum types, the visitor pattern exists to add operations to a type hierarchy. Rust's enums and match usually make it unnecessary, with a few exceptions.
Tag
6 posts

In languages without sum types, the visitor pattern exists to add operations to a type hierarchy. Rust's enums and match usually make it unnecessary, with a few exceptions.

Rust forbids adding inherent methods to foreign types, but a trait you define can. Extension traits are how itertools, futures and tokio add methods to the standard library.

A tuple struct with one field costs nothing at runtime and stops you passing a user id where an order id belongs. Learn construction, derives, Deref pitfalls and the orphan rule workaround.

Implement undo and redo in Rust with the command pattern: commands as an enum, execute and undo methods, history stacks, merging, and a text editor example.

A repository hides the database behind a trait. See when that helps (testing, swapping stores) and when it only adds indirection, with a concrete trait, an SQLx impl and an in-memory fake.

Rust match is exhaustive: the compiler checks every case. Learn literals, ranges, guards, bindings, tuple, struct and slice patterns with working examples.