Urgent.News

What's breaking now, across thousands of outlets.

Tech

A Type Stronger than the Sum of its Components

Ever crafted a type so exceptional that it lingers in your thoughts, akin to savoring an exquisite dish? The author experienced such a moment with Rust, sharing their delight in transforming an enum with N variants into N distinct types. The `std::path::Component` enum, derived from any `std::path::Path` reference, proves particularly useful for breaking down and manipulating paths.

However, an interface accepting any component type proves overly broad and impractical. To address this, the author created owned structs for each component type, allowing them to write functions with precise type guarantees. For instance, a function signature using `NormalComponent` ensures that joining it to an absolute path will yield another absolute path.

This approach also aids in representing entries within directories. The author discovered that enums, often referred to as "sum types," can provide valuable insights into specific instances of a broader type. They've since found various applications for this abstraction, yet they admit it might not be earth-shattering. Nonetheless, the author finds it gratifying to have a tool that enables precise type handling and avoids potential pitfalls when working with paths.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at schneems.com →

More in Tech

More from Friday 25 September →