1
0
Fork
You've already forked applying
0
Apply functions in method-position.
  • Rust 100%
Find a file
2024年08月07日 11:09:54 +09:00
src docs: generate README 2024年07月03日 15:25:37 +09:00
.gitignore Initial commit 2024年07月03日 15:18:35 +09:00
Cargo.lock release: 1.0.1 2024年08月07日 11:08:43 +09:00
Cargo.toml legal: correct the SPDX identifier 2024年08月07日 11:09:54 +09:00
CHANGELOG.md release: 1.0.1 2024年08月07日 11:08:43 +09:00
LICENSE legal: LGPL -> MPL 2024年08月07日 11:06:46 +09:00
README.md docs: generate README 2024年07月03日 15:25:37 +09:00

Apply functions in method-position.

The Problem

Much functionality in Rust is provided by methods, but occasionally we're forced to use certain standalone functions. Examples are functions like [std::str::from_utf8] or [std::sync::Arc::new]:

letuser=fetch_user().await.map_err(Error::UserIsLost)?;letarc=Arc::new(user);Ok(arc)

Many functions that we write are also effectful, and require us to wrap some final value in an Ok. The combination of these factors means that we often have to bind values to names, even when we don't want to. Naming is hard, and bad names can cause confusion for later readers. In the above, who benefits from seeing a symbol named arc? Names should reflect what something is, not what it's wrapped in.

And what if the only appropriate name would be the one it already had, say in the case of a "response" value, etc.? This encourages "variable shadowing", as in:

letresp=make_request(req).await?;letresp=foo(resp);letresp=bar(resp);

This code is fragile to ownership and refactors. We shouldn't have to write code that looks like this.

The Solution

This library provides the trait [Apply], which exposes an apply method that is injected into all types via a "blanket implementation". apply allows you to call top-level functions in a chain with the rest of your method calls. This way, the original example becomes:

fetch_user().await.map_err(Error::UserIsLost)?.apply(Arc::new).apply(Ok)

Ah, beautiful, consistent nesting. And no spurrious names to confuse the peasantry.