RunAwayFrog@sh.itjust.workstoRust@programming.dev•Getting into rust and could use some pointers
4·
1 year agoMy quick notes which are tailored to beginners:
Use Option::ok_or_else()
and Result::map_err()
instead of let .. else
.
let .. else
didn’t always exist. And you might find that some old timers are slightly triggered by it.- Functional style is generally preferred, as long as it doesn’t effectively become a code obfuscater, like over-using
Option
s as iterators (yesOption
s are iterators). - Familiarize yourself with the
?
operator and theTry
trait
Type inference and generic params
let headers: HashMap = header_pairs
.iter()
.map(|line| line.split_once(":").unwrap())
.map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
.collect();
(Borken sanitization will probably butcher this code, good thing the problem will be gone in Lemmy 0.19)
Three tips here:
- You don’t need to annotate the type here because it can be inferred since
headers
will be returned as a struct field, the type of which is already known. - In this pattern, you should know that you can provide the collected type as a generic param to
collect()
itself. That may prove useful in other scenarios. - You should know that you can collect to a
Result
/Option
if the iterator items areResult
s/Option
s. So that.unwrap()
is not an ergonomic necessity 😉
Minor point
- Use
.into()
or.to_owned()
for&str => String
conversions.- Again, some pre-specialization old timers may get slightly triggered by it.
make good use of the crate echo system
- It’s important to make good use of the crate echo system, and talking to people is important in doing that correctly and efficiently.
- This post is a good start.
- More specifically, the
http
crate is the compatibility layer used HTTP rust implementations. Check it out and maybe incorporate it into your experimental/educational code.
Alright, I will stop myself here.
Here is an originally random list (using
cargo tree --prefix=depth
) with some very loose logical grouping. Wide-scoped and well-known crates removed (some remaining are probably still known by most).mime data-encoding percent-encoding textwrap unescape unicode-width scraper arrayvec bimap bstr enum-iterator os_str_bytes pretty_assertions paste clap_complete console indicatif shlex lz4_flex mpeg2ts roxmltree speedy aes base64 hex cbc sha1 sha2 rsa reverse_geocoder trust-dns-resolver signal-hook signal-hook-tokio blocking fs2 semver snmalloc-rs