Use Rust’s Option type and its methods effectively to handle nullable values. This improves code clarity and safety by making null cases explicit and leveraging the type system.
Key practices:
Example - Before:
// Using tuple return
fn is_pragma_comment(comment: &str) -> (bool, usize) {
// Returns (is_pragma, offset)
if comment.contains("pragma") {
(true, comment.find("pragma").unwrap_or(0))
} else {
(false, 0)
}
}
After:
// Using Option for clearer semantics
fn is_pragma_comment(comment: &str) -> Option<usize> {
// Returns offset if comment is pragma, None otherwise
comment.contains("pragma").then(|| {
comment.find("pragma").expect("pragma exists")
})
}
// Usage with appropriate Option methods
let offset = is_pragma_comment(comment)
.unwrap_or_default(); // Use default when None
This approach:
Enter the URL of a public GitHub repository