Rust API Design: Why Blanket Trait Impls for References Matter
A technical guide on DEV Community explains that Rust does not automatically implement a trait for references to a type, even when the base type already implements it. This can surprise developers who expect &Bar to satisfy a trait bound when Bar does, violating what the author calls the 'unsurprising' API design principle. To address this, the guide recommends manually providing blanket implementations for &T, &mut T, and Box<T> wherever trait methods permit. The article also covers implementing IntoIterator for borrowed and mutable references so collections can be used naturally in for-loops. Additionally, it touches on how Deref and AsRef can simulate inheritance-like behavior in Rust's type system.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in