精炼:Rust 的简单细化类型

  • Introduction: The author has been working on refined library for a few months and released an initial alpha version. It provides better support for refinement types in Rust. The crate documentation is good, and the author wants to explain the motivation and problems the library solves.
  • What is refinement: Refinement narrows the possible set of values for a type. It's useful for modeling domain invariants within the type system, improving documentation and maintainability while preventing bugs.
  • A contrived example: Using refined, a test score can be modeled as a Refinement over u8 with a specific range. Creating and using values of the refined type is easy, but there is a small runtime cost. An enum with 100 variants is the most correct way to model the test score, but it's often avoided.
  • Parse, don't validate: Parsing is different from validation. A parser consumes less-structured input and produces more-structured output, and all parsers must have a notion of failure. With refined, by having an Output, invariants are guaranteed to be met. When using refinement types with serde, the essence of "parse, don't validate" is achieved.
  • Wrapping up: This is a quick tour of the motivation for creating refined. Check the crate documentation for more information. If there are any issues or ideas for improvement, open an issue.
  • Follow for new post notifications: Enjoyed the post? Consider following for new post notifications.
阅读 10
0 条评论