316 private links
But after programming in Rust for 10 years, I think that your coding style has the biggest impact on how your Rust code will look and feel.
People often say Rust’s syntax is ugly, but I’d argue the syntax is the least interesting thing about Rust. The semantics (the bits and pieces the language provides to express your ideas and how those bits combine to build interesting things) are much more important.
Parsing a .env can be clunky in basic algorithm, but elegant in Rust.
Tips:
read_to_string()instead of using a path, opening a file, creating a vector, adding the content to the vector to make a string- Use type inference:
let mut cfg = HashMap::new() - Lean into the typesystem:
.lines()to split strings safely and iterates over the linessplit_once()to get each key-value pair for each lines
- leverage error handling: use an enum to list all possible errors with important values and
thiserrorcan handle the error message
fn parse_config_file(path: &str) -> Result<HashMap<String, String>, ParseError> {
let content = read_to_string(path)?;
let mut config = HashMap::new();
for line in content.lines() {
match KeyValue::try_from(line) {
Ok(kv) => { config.insert(kv.key, kv.value); },
Err(ParseError::InvalidLine(_)) => continue, // Skip invalid lines
Err(e) => return Err(e), // Fail on any other error
}
}
Ok(config)
}
and why this code structure offers more extensibility!
Rust’s beauty is in its semantics and the core mechanics it provides: ownership, borrowing, pattern matching, traits, and so on. If you merely look at its (admittedly foreign) syntax, you overlook the real elegance of the language.
If there is anything that makes Rust “ugly”, it isn’t its syntax but the fact that it doesn’t hide the complexity underneath. Rust values explicitness and you have to deal with the harsh reality that computing is messy. Turns out our assumptions about a program’s execution are often wrong and our mental models are flawed.
Fortunately, we can encapsulate a lot of the complexity behind ergonomic abstractions; it just takes some effort! So don’t worry: once you start to confront your bad habits and look around for better abstractions, Rust stops being ugly.