1 unstable release
0.1.0 | Dec 10, 2019 |
---|
#2102 in Rust patterns
4KB
ufcs.rs
ufcs::Pipe
— helper trait to call free functions using method call syntax.
Rust already allows calling methods using function call syntax, but not the other way around.
This crate fills the gap by providing a simple helper trait Pipe
.
Usage
Cargo.toml:
[dependencies]
ufcs = "0.1.0"
Rust code:
use ufcs::Pipe;
Examples
// Write this
foo().pipe(bar).pipe(baz);
// Instead of this
baz(bar(foo()));
// Write this
let text: String = reqwest::get("http://httpbin.org/get")
.await?
.json::<serde_json::Value>()
.await?
.pipe(toml::Value::try_from)?
.pipe(|x| toml::to_string(&x))?;
// Instead of this
let text: String = toml::to_string(&toml::Value::try_from(
reqwest::get("http://httpbin.org/get")
.await?
.json::<serde_json::Value>()
.await?,
)?)?;
See tests for more examples.
See also
Roughtly the same feature is either implemented or proposed in various languages.
Rust
pipeline.rs
: implemented as an macro- RFC #289: Unified function / method call syntax
- RFC #2049: Piping data to functions
- Method-cascading and pipe-forward operators proposal
- Rust #44874: Tracking issue for
arbitrary_self_types
Other languages
- https://en.wikipedia.org/wiki/Uniform_Function_Call_Syntax
- Nim, DLang: built-in UFCS
- F#, Elixir: the pipe operator
|>
- C++: proposed