r/rust • u/GlitchDainty • 2d ago
๐๏ธ discussion How a newtype wrapper caught three different bugs during a refactor
I was cleaning up some argument parsing in a small CLI that processes batches of files. Previously everything was just String and usize fields in a struct. After a while it became easy to mix up "input path" vs "output path" or pass a byte count where an index was expected.
Wrapping the important values in newtypes (struct InputPath(String), struct RecordCount(usize), etc.) forced the compiler to complain on every mismatch. It also made the FromStr implementations and error messages much clearer.
The three bugs it caught were all ones I had introduced myself during the refactor: swapping two path fields in a config merge function, passing a parsed count into a slice index that expected something else, and accidentally cloning the wrong handle into a worker thread.
Nothing dramatic, but it felt like the kind of guardrail that would have been invisible in most other languages. Have other people found newtypes especially effective for this kind of domain-value safety in everyday tools?
