# Method chaining special form

**URL:** <https://internals.rust-lang.org/t/method-chaining-special-form/342>\
**Category:** ideas (deprecated)\
**Created:** [August 6, 2014, 8:30pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342 "2014-08-06T20:30:44Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![Gankra](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/gankra/32/6002_2.png) [@Gankra](https://internals.rust-lang.org/u/Gankra)\
**Post date:** [August 6, 2014, 8:30pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/1 "2014-08-06T20:30:45Z")

</div>

A few methods have slipped in that, as far as I can tell, are just to make method chaining more convenient. In particular, `Vec.append_one` is just a `push` that returns `self` afterwards. Rather than bloat up the API with lots of similar-but-subtly-different methods, I’d prefer if this pattern were generalized to something reusable.

Ruby has [tap](http://seejohncode.com/2012/01/02/ruby-tap-that/) for exactly this, and tap could be implemented pretty easily in Rust, though it’s exceptionally verbose:

```rust
//Stolen from kimundi

trait Tap { 
    fn tap(mut self, f: |&mut Self|) -> Self { 
        f(&mut self); 
        self 
    } 
} 

impl<T> Tap for T {} 

fn main () {
    let v = vec![1u, 2, 3]; 
    v.tap(|v| v.push(100)).tap(|v| v.push(1024));
}

```

([on play](http://is.gd/q85Nhi))

An actual special form like a `..` or `->` operator would probably be more friendly, although Mo’ Sigils Means Mo’ Problems.

Regardless, it would just be a trivial sugar for `foo.bar(); foo`, and usage would look like:

```rust
foo..push(1)..push(2)..push(3)
foo->push(1)->push(2)->push(3)
foo(╯°□°）╯︵push(1)(╯°□°）╯︵push(2)(╯°□°）╯︵push(3)

```

---

<div class="post-metadata">

**Author:** ![dobkeratops](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/dobkeratops/32/4577_2.png) [@dobkeratops](https://internals.rust-lang.org/u/dobkeratops)\
**Post date:** [August 7, 2014, 2:57am UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/3 "2014-08-07T02:57:38Z")

</div>

could a macro handle this

---

<div class="post-metadata">

**Author:** ![Valloric](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/valloric/32/9611_2.png) [@Valloric](https://internals.rust-lang.org/u/Valloric)\
**Post date:** [August 7, 2014, 4:32am UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/4 "2014-08-07T04:32:27Z")

</div>

A bit of sugar here goes a long way. [Dart has the `..` operator](https://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#classes). I’d love to see something like this in Rust.

---

<div class="post-metadata">

**Author:** ![eddyb](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/eddyb/32/8411_2.png) [@eddyb](https://internals.rust-lang.org/u/eddyb)\
**Post date:** [August 7, 2014, 9:52am UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/5 "2014-08-07T09:52:52Z")

</div>

One reason I would prefer not to use `..` for this is that I had an idea about making `a..b` sugar for `range(a, b)`, which would be usable for things like `v[a..b]`, without requiring a special slicing operator, just `range` sugar and overloaded `Index`.

---

<div class="post-metadata">

**Author:** ![Kimundi](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kimundi/32/180_2.png) [@Kimundi](https://internals.rust-lang.org/u/Kimundi)\
**Post date:** [August 7, 2014, 6:38pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/6 "2014-08-07T18:38:16Z")

</div>

It is possible with a macro if you don’t mind the outer invocation syntax:

```rust
macro_rules! meth_chain(
    ($inp:expr $(-> $call:ident($($e:expr),*))*) => (
        {
            let mut tmp = $inp;
            $(
                tmp.$call($($e),*);
            )*
            tmp
        }
    );
    ($inp:expr $(-> $call:ident::<$($t:ty),*>($($e:expr),*))*) => (
        {
            let mut tmp = $inp;
            $(
                tmp.$call::<$($t),*>($($e),*);
            )*
            tmp
        }
    )
)

fn main() {
    let a = vec![1u, 2, 3];
    let b = meth_chain!(a->push(50));
    let c = meth_chain!(
        b->push(50)
         ->push(100)
         ->push(150)
    );

    assert_eq!(c, vec![1, 2, 3, 50, 50, 100, 150])
}

```

[playpen](http://is.gd/tzlXw1)

---

<div class="post-metadata">

**Author:** ![glaebhoerl](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/glaebhoerl/32/1978_2.png) [@glaebhoerl](https://internals.rust-lang.org/u/glaebhoerl)\
**Post date:** [August 7, 2014, 11:03pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/7 "2014-08-07T23:03:54Z")

</div>

Is there any reason for `push` itself, and similar methods, not to return `&mut Self`?

---

<div class="post-metadata">

**Author:** ![steveklabnik](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steveklabnik/32/4524_2.png) [@steveklabnik](https://internals.rust-lang.org/u/steveklabnik)\
**Post date:** [August 7, 2014, 11:41pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/8 "2014-08-07T23:41:57Z")

</div>

HKT + monads == done 😉

---

<div class="post-metadata">

**Author:** ![Kimundi](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kimundi/32/180_2.png) [@Kimundi](https://internals.rust-lang.org/u/Kimundi)\
**Post date:** [August 8, 2014, 11:46am UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/9 "2014-08-08T11:46:33Z")

</div>

@glaebhoerl: That leads to these problems:

1. The library writer always has to keep in mind all possible conventions for chaining, which will lead to inconsistency because he will forget or not bother.
2. Methods no longer do just their thing, they do their thing + something unrelated that is only useful in comparatively rare cases.
3. Its not possible for all methods that might need this. For example, `remove()` on a set would return a `bool` indicating whether the element was actually in there, which would be incompatible with this scheme

---

<div class="post-metadata">

**Author:** ![glaebhoerl](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/glaebhoerl/32/1978_2.png) [@glaebhoerl](https://internals.rust-lang.org/u/glaebhoerl)\
**Post date:** [August 8, 2014, 1:32pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/10 "2014-08-08T13:32:40Z")

</div>

The idea was that this would be an easy 80% solution that could be achieved merely through convention. The motivating thought is, essentially: why are we trying to come up with technical workarounds for our modifier-methods not supporting chaining, instead of making them support chaining?

Basically we would have the convention that modifier methods taking `&mut self` shouldn’t return `()`, they should return a useful result instead, namely `&mut Self`. This addresses your first point: conventions are inherently things library writers need to keep in mind, and this would be a fairly simple one. (We could even have a lint, if we really wanted to.) This wouldn’t solve every case, for instance it wouldn’t work for methods like `remove()` which return additional information, but it would work for quite a lot of them, and would remove most of the pain at no cost to the language itself.

---

<div class="post-metadata">

**Author:** ![Gankra](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/gankra/32/6002_2.png) [@Gankra](https://internals.rust-lang.org/u/Gankra)\
**Post date:** [August 8, 2014, 1:54pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/11 "2014-08-08T13:54:46Z")

</div>

There’s some pseudo-back-compat issues here. If I have a method that returns nothing, I don’t think many people will have a lot of trouble if I start making it return something. Recompiles will of course be necessary, and an extra semicolon might need to be added here or there, but client code shouldn’t be very disrupted. However, if I have a method that returns `self` because “why not”, and then I want to start returning something meaningful, then that’s a much more serious change.

As an example, there’s some leaning towards having little-to-no collection traits circa 1.0, because generic collections simply won’t work right at that point in time. So maybe `Vec` and whoever have their own `push` operation that always succeeds, but some collections have a `push` that potentially isn’t as clean (e.g. fixed-size collections) and thus returns something relevant. Eventually we decide to introduce some unifying traits and, oops, we had `Vec.push` returning `self` “because we could”.

More generally, though, a uniform convention/syntax just seems desirable for programmer sanity.

---

<div class="post-metadata">

**Author:** ![glaebhoerl](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/glaebhoerl/32/1978_2.png) [@glaebhoerl](https://internals.rust-lang.org/u/glaebhoerl)\
**Post date:** [August 8, 2014, 5:07pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/12 "2014-08-08T17:07:13Z")

</div>

@Gankro Good points. It should be noted though that `Vec` wouldn’t need to lose its own `push` just because it later ended up also implementing some unifying trait. If the signatures of the `push`es differred, the result would be some inconsistency, but not a backwards compatibility problem per se.

---

<div class="post-metadata">

**Author:** ![sinistersnare](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/sinistersnare/32/18_2.png) [@sinistersnare](https://internals.rust-lang.org/u/sinistersnare)\
**Post date:** [August 8, 2014, 6:59pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/13 "2014-08-08T18:59:56Z")

</div>

+1 for `..` syntax which Dart uses. Its very nice and simple, and improves readability immensely.

---

<div class="post-metadata">

**Author:** ![dobkeratops](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/dobkeratops/32/4577_2.png) [@dobkeratops](https://internals.rust-lang.org/u/dobkeratops)\
**Post date:** [August 8, 2014, 7:44pm UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/14 "2014-08-08T19:44:21Z")

</div>

-1 for `..` - +1 for keeping `..` free for ranges, like swift, and analogous to the [T…N] -1 for `->` - it will confuse the hell out of a C++ conditioned mind… keep it for functions .

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [March 25, 2019, 8:09am UTC](https://internals.rust-lang.org/t/method-chaining-special-form/342/15 "2019-03-25T08:09:01Z")

</div>

Closed on March 25, 2019, 8:09am UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
