[Advanced Rust] 2.9. API Design Principles of Obviousness - Documentation and Type System, Semantic Types, and Zero-Sized Types
2.9.1. Documentation and the Type System Users may not fully understand all of an API's rules and restrictions. So your API should be easy for users to understand and hard to misuse. With Rust's documentation and type system, we can try to achieve that. 2.9.2. Documentation The first step toward making an API transparent is to write good documentation . Writing good documentation has several…
2.9.1. Documentation and the Type System
When users may not fully comprehend an API's rules and limitations, it is crucial for the API to be easily understandable and difficult to misuse. Good documentation and a robust type system in Rust can help achieve this goal.
2.9.2. Documentation
To make an API transparent, it is essential to write clear documentation. This documentation should clarify any unexpected situations or behaviors that may depend on the user performing actions beyond the type signature. For instance, it should specify when a panic might occur or when an error is returned. If an unsafe function is used, the conditions under which a user can safely call it must be explained.
Examples are also crucial at the crate or module level. They help users understand how the components fit together and provide a clear overview of the API's structure. This makes it easier for developers to grasp the purpose of each method and type and where they can be used. After presenting an end-to-end example, users can copy and paste the code into their projects, creating a tailored starting point.
In addition to documenting types and methods, organizing the documentation well is vital. Modules should be used to group semantically related items, and internal documentation links should connect them. Sometimes, the `#[doc(hidden)]` attribute can be used to mark interfaces that are not meant to be public but are retained for legacy reasons, preventing clutter in the documentation.
Further enrichment of the documentation is encouraged. External resources, such as RFCs, blogs, and white papers, can be linked to help users understand the underlying principles and algorithms. Additionally, at the top-level documentation, users should be guided to common modules, traits, types, and methods. Some notes about documentation features include using `#[doc(cfg(..))]` to highlight items available only under specific configurations and `#[doc(alias = "...")]` to allow users to search for types or methods under alternative names.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — it may contain errors, so check the original before relying on it.