Design your API using struct for data, impl blocks for methods, and Result<T, E> for error handling to ensure safety and clarity.
struct User {
username: String,
email: String,
}
impl User {
fn new(username: String, email: String) -> Result<Self, String> {
if username.is_empty() {
return Err("Username cannot be empty".to_string());
}
Ok(User { username, email })
}
}
This pattern uses the struct definition to group related fields, the impl block to define the new constructor, and returns a Result to handle validation errors explicitly.