The problem
In fix-rs, a FIX protocol engine I'm writing in Rust, a market data request carries the currency pair inside a repeating group:
35=V|262=REQ-1|263=0|264=1|267=2|269=0|269=1|146=1|55=EUR/USD|
The generated typed API returns an Option for each step that might be missing:
// On MarketDataRequest: returns the NoRelatedSym repeating group (tag 146),
// or None if the request doesn't have one.
fn no_related_sym(&self) -> Option<NoRelatedSym<'_>>;
// On NoRelatedSym: returns entry i of the group as a NoRelatedSymEntry,
// or None if there's no entry at that index.
fn get(&self, i: usize) -> Option<NoRelatedSymEntry<'_>>;
// On NoRelatedSymEntry: returns the entry's Symbol (tag 55), the currency pair,
// or a FieldError if it's missing or malformed.
fn symbol(&self) -> Result<String, FieldError>;
If there's no pair, the handler has to reply with a business reject naming tag 146. My first
version:
let entry = req.no_related_sym().unwrap().index(0);
It gets the value out, but says nothing about what a missing value should mean.
The same shape, everywhere in Rust
Strip away the FIX details and the problem is:
I have an
Option<T>. If there's a value, run something on it to get aU. If there's no value,
or the step fails or produces something invalid, return an error. Otherwise give me theU.
Rust hands you this shape all the time:
-
HashMap::get(&key)→Option<&V>, then parse or validate the value. -
iter().next(),slice.first(),vec.last()→Option<&T>, then use it. -
str::split_once(':'),strip_prefix("v")→Option<..>, then parse the pieces. -
std::env::var("PORT").ok()→Option<String>, thenparse::<u16>(). -
args.next()for a CLI argument, then convert it. - A typed API's optional field or group, like the FIX one above.
Each time the code has to do the same three things:
-
Get the value out of the
Option. - Transform it: call a method, parse it, look something up.
- Decide what absence or failure means, and turn it into your error.
Nested match / if let can do all three, but the useful line ends up three levels deep.
unwrap() does the first two and skips the third. The standard library has a small set of
combinators that do all three in one readable chain.
The building blocks
| Method | Turns | Use when |
|---|---|---|
.map(f) |
Option<T> → Option<U>
|
f can't fail: T -> U
|
.and_then(f) |
Option<T> → Option<U>
|
f can also come back empty: T -> Option<U>
|
.filter(p) |
Option<T> → Option<T>
|
the value can be present but invalid |
.ok_or(e) / `.ok_or_else(\ |
\ | e)` |
? |
Result<T, E> → T, or return Err(e) early |
inside a function returning Result
|
.map_err(f) |
Result<T, E1> → Result<T, E2>
|
translate a lower-level error into yours |
.transpose() |
Option<Result<T, E>> ↔ Result<Option<T>, E>
|
absence is fine, present-and-broken isn't |
ok_or is the important one. It's the point where "nothing there" becomes "here's why that's a
problem", and ? then does the early return.
Recipes
Pick the recipe by what your transform step returns.
Recipe 1: the step can also come back empty → and_then + ok_or
This is the fix-rs case. get(0) returns an Option, so the steps chain with and_then:
let entry = req
.no_related_sym() // Option<NoRelatedSym>
.and_then(|syms| syms.get(0)) // Option<NoRelatedSymEntry>
.ok_or(BusinessMsgReject::MissingConditionallyRequiredField { tag: 146 })?;
map would give Option<Option<_>> here, because get already returns an Option. and_then
flattens it, and the first None short-circuits the rest. "Group missing" and "group present but
empty" become the same None and get the same reject. That's only possible because the API offers
get (returns Option) next to index (panics).
Recipe 2: the step has its own error → ok_or + ?, then map_err + ?
The last step in fix-rs, symbol(), returns Result<String, FieldError>. If I wanted a malformed
symbol to get its own reject instead of trusting the parser, the chain continues:
let ccy_pair = req
.no_related_sym()
.and_then(|syms| syms.get(0))
.ok_or(BusinessMsgReject::MissingConditionallyRequiredField { tag: 146 })? // absent
.symbol()
.map_err(|_| BusinessMsgReject::MissingConditionallyRequiredField { tag: 55 })?; // bad
Two failure modes, two different errors, one chain. The same recipe outside FIX:
let port: u16 = cfg
.get("port")
.ok_or(ConfigError::Missing("port"))? // absent -> Missing
.parse()
.map_err(ConfigError::BadPort)?; // present but not a number -> BadPort
Recipe 3: the step can't fail → map + ok_or
let name_len = cfg.get("name").map(|s| s.len()).ok_or(ConfigError::Missing("name"))?;
Recipe 4: present but must be valid → filter + ok_or
let workers = cfg
.get("workers")
.and_then(|s| s.parse::<usize>().ok())
.filter(|n| *n > 0)
.ok_or(ConfigError::Invalid("workers must be a positive number"))?;
filter turns "present but invalid" into None, so the single ok_or covers missing,
unparseable and zero.
Recipe 5: optional, but must be valid if present → map + transpose
let timeout: Option<u64> = cfg
.get("timeout")
.map(|s| s.parse::<u64>()) // Option<Result<u64, _>>
.transpose() // Result<Option<u64>, _>
.map_err(ConfigError::BadTimeout)?; // Option<u64>
No timeout is fine; timeout = "soon" is an error.
The statement form: let ... else
Stable since Rust 1.65. It binds the value or leaves the function, and the happy path stays at the
outer indentation level. This is what fix-rs ended up with:
let Some(entry) = req.no_related_sym().and_then(|syms| syms.get(0)) else {
return Err(BusinessMsgReject::MissingConditionallyRequiredField { tag: 146 });
};
let ccy_pair = entry.symbol().expect("Symbol is NoRelatedSym's first field");
It's the same idea as Recipe 1. Reach for it when the chain gets long, when you need the
intermediate value (entry) for more than one thing, or when the else block needs to do more
than build an error (log, count, clean up).
Where the code lives is part of the solution
? only works inside a function that returns Result (or Option). In fix-rs, the snapshot
builder returned a plain message, so it couldn't use ?. That's why it had unwrap() in the first
place.
The fix wasn't to make the builder fallible. It was to move the lookup up into the message handler,
which already returns Result<Vec<Message>, BusinessMsgReject>, and pass the builder plain values:
// handler: may fail, decides what failure means
let Some(entry) = /* ... */ else { return Err(/* ... */) };
let snapshot = self.build_md_snapshot(&req_id, &ccy_pair);
// builder: can't fail, just builds
fn build_md_snapshot(&self, req_id: &str, ccy_pair: &str) -> MarketDataSnapshotFullRefresh
The pattern pushes "get, check, decide" to the boundary (a request handler, a config loader,
main), and everything below takes values that are already valid. A helper with unwrap() inside
is often asking to have its lookup moved up to the caller.
ok_or or expect?
The let ... else example still ends in expect, on purpose. FIX's parser guarantees every entry
in this group starts with a Symbol, so symbol() can't fail there. The two tools say different
things:
-
ok_or/let ... else: this can happen, and here's what it means. -
expect: this can't happen, and here's why (the message is the reason).
Most of the work is deciding which one you're in. If you can't explain why it can't happen, it's
an ok_or.
Takeaways
- "Option in, value or error out" is one of the most common shapes in Rust code.
- Pick the combinator by what your step returns:
and_then(Option),map(plain value),filter(validity),transpose(optional but must be valid if present). - Convert absence into an error once, with
ok_or, where you know what it means.?returns it. -
let ... elseis the statement form of the same idea. -
?pushes validation to your code's boundary; the code below takes plain, valid values. -
expectis for what can't happen, not for what you hope won't.
Top comments (0)