# A shorthand for implementing traits

**URL:** <https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195>\
**Category:** language design\
**Created:** [August 18, 2021, 5:45pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195 "2021-08-18T17:45:44Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![T-O-R-U-S](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/t-o-r-u-s/32/8156_2.png) [@T-O-R-U-S](https://internals.rust-lang.org/u/T-O-R-U-S)\
**Post date:** [August 18, 2021, 5:45pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195/1 "2021-08-18T17:45:44Z")

</div>

A shorthand for implementing traits, that would turn code that looks like this:

```rust
trait SuperCoolTrait {
  fn myFunction(&self);
}

// Implementing the type itself
impl MyType {
  fn function() {
    unimplemented!()
  }
}

// Implementing trait for the type

// Duplicating the type's name name (bad for maintainability),
// Extra typing that could be avoided
impl SuperCoolTrait for MyType {
  fn myFunction(&self) {
    unimplemented!()
  }
}

```

into this:

```rust
trait SuperCoolTrait {
  // --snip--
}

// Maybe it should be closer to `impl MyType with SuperCoolTrait`
// for increased clarity over which traits the type implements at
// first glance.
impl MyType {
  fn function() {
    unimplemented!()
  }

  // Prefix with trait keyword?
  // trait SuperCoolTrait { /* --snip-- */ }
  // Feel like this would cause ambiguity though,
  // for humans AND the compiler
  SuperCoolTrait {
    fn my_function(&self) {
      unimplemented!()
    }
  }
  FooTrait {
    fn foo_function() {

    }
  }
}

```

This shorthand just looks much cleaner (in my personal opinion), duplicates names less (if you are renaming a struct, that is one less place(s?) to rename).

I want to know what you guys think of such a design and if you have anything to add to the conversation.

The biggest drawback I see to this shorthand is that it risks making it less clear which types implement which traits. Perhaps the `impl` should be more like `impl MyType **with SuperCoolTrait** ` (no asterisks) to make it more obvious that this type implements the given trait.

The reason I decided to nest these inside of their trait names instead of have them be at the top level of the `impl` is to preserve clarity about which functions are part of which traits. This does **not** mean that you would have to do `thing.SuperCoolTrait.my_function()` to access a function in a trait.

Declaring function with the same name at the top-level of the `impl` should be disallowed (for obvious reasons)

I feel like all of these can drastically cut down on the amount of typing, but can also reduce the amount of places in which you have to rename a struct/enum if you have implemented several traits for it.

Let me know what you think, and why this is potentially a _bad_ idea!

---

<div class="post-metadata">

**Author:** ![H2CO3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/h2co3/32/2849_2.png) [@H2CO3](https://internals.rust-lang.org/u/H2CO3)\
**Post date:** [August 18, 2021, 6:04pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195/2 "2021-08-18T18:04:51Z")

</div>

Since this thread came from URLO, for the sake of completeness, let me add a backlink to my post describing why I oppose this idea: [link](https://users.rust-lang.org/t/feature-idea-new-way-to-use-impl-for-to-reduce-code-duplication/63738/2)

---

<div class="post-metadata">

**Author:** ![mbrubeck](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mbrubeck/32/174_2.png) [@mbrubeck](https://internals.rust-lang.org/u/mbrubeck)\
**Post date:** [August 18, 2021, 6:42pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195/3 "2021-08-18T18:42:39Z")

</div>

One disadvantage of this shorthand is that it can't replace all uses of the existing `impl Trait for Type` syntax. For example, it doesn't work when the type and the impl are defined in different crates—unless we start allowing `impl Type { ... }` for foreign types with added restrictions.

Even if we could theoretically deprecate the original syntax, it would affect so much existing code that it is almost certainly too big a change in practice. Regardless, the old syntax would live on in code and docs written in the current edition of Rust. Every time we add two ways to do the same thing, it adds another bit of minor complexity for Rust learners.

(Yes, this is a general argument that applies to _any_ new syntax sugar, so it should always be weighed against other factors.)

> [@T-O-R-U-S](#):
>
> I feel like all of these can drastically cut down on the amount of typing, but can also reduce the amount of places in which you have to rename a struct/enum if you have implemented several traits for it.

The reduction in typing seems minor (it saves one or two words per trait impl). Meanwhile, the number of lines is either the same or _higher_ than the existing syntax, and the increased nesting uses more horizontal space as well.

Yes, it reduces the number of places affected by renaming the type, but most IDEs can rename a type automatically.

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [August 18, 2021, 7:36pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195/4 "2021-08-18T19:36:33Z")

</div>

This has previously been discussed; I specifically recall this thread, though I also think @Soni has mentioned it more recently. (Side note: linking is for context purposes only, and not endorsement of any specific author or post in linked thread. (Note: this disclaimer is not trying to put down any author or post in the linked thread.))

> [@\[pre-pre-RFC\] \`impl trait\` inside \`impl\`, treating trait impls as sort-of inherent items](https://internals.rust-lang.org/t/pre-pre-rfc-impl-trait-inside-impl-treating-trait-impls-as-sort-of-inherent-items/14056):
>
> Idea Instead of impl Foo { /// docs go here fn foo() {} } impl Trait for Foo { } One would be able to write: impl Foo { /// docs go here fn foo() {} /// more docs here impl trait Trait { } } There are a few benefits to this: Less generic boilerplate (see below). Encouraging more docs. Eh that's about it really. There are a few drawbacks to this, tho: Extra indentation. There are also some tradeoffs that can be had: It could be just "impl Trait", but the choice of using …

While the amount of redundant typing (note: typing as in types in the language, not keyboard typing) reduction is limited in the simple case, more interesting bounds on generic types can lead to a lot of duplicated type information for multiple trait impls.

Additionally, `impl Type { impl Trait { fn foo() {} } }` is potentially useful as an _inherent_ impl, where the `Trait` functions are available for `Type` even without bringing `Trait` into scope, equivalently to if extra forwarding inherent impls were provided. (Including precluding a separate inherent impl with the same name.)

Implied bounds for inherent trait bounds would reduce again the benefit of deduplicating the typing overhead, but there are still cases where the ideal situation of bound-free type definitions and bounded impls are useful and would reduce typing overhead there.

The main downside I can see, though, is that the deduplicating would encourage over-bounded trait impls, as it'd be easier to provide one superset bounded `impl` and impl all traits inside it, than implement the traits separately with proper bounds.

I still personally like the idea, but if and only if the functions are (all) also provided as inherent functions. This meaningfully separates it from the separate item case (which it desugars to).

---

<div class="post-metadata">

**Author:** ![Soni](https://avatars.discourse-cdn.com/v4/letter/s/a3d4f5/32.png) [@Soni](https://internals.rust-lang.org/u/Soni)\
**Post date:** [August 18, 2021, 7:58pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195/5 "2021-08-18T19:58:49Z")

</div>

tl;dr: It interacts badly with existing macros.

Personally, we'd much rather love to see a proposal to enable

```rust
#[impl_trait]
impl Foo {
  // contents are opaqueified so the proc attribute macro can do more things
}

```

which would make our crate better by removing a whole level of nesting, and hopefully work better with existing macros. Specifically, currently `impl_trait::impl_trait!` doesn't let you nest other similar macros, but the attribute variation would let you (altho success is dependent on various other factors).

```rust
impl_trait! {
  this_doesnt_work! {
    // mainly the problem is that we expect a bunch of attributes and an
    // impl block, but instead we're met with a macro.
  }
}

```

There is some value in bringing `impl_trait!`'s syntax to the compiler tho, in one particular place: docs. Currently trait impls are seen as "extrinsic" to the type. For example, for [Cursor in std::io - Rust](https://doc.rust-lang.org/std/io/struct.Cursor.html), only `get_mut`, `get_ref`, `into_inner`, `new`, `position` and `set_position` are considered "intrinsic" features of the `Cursor`, with the trait impls all being moved together to their own section of "extrinsic" features. Being able to put trait impls inside inherent impls (_even if it requires using the full existing syntax_) would enable you to say, "These trait impls are important features of this type, you are probably interested in using them almost every time you use this type.". This could even enable deprecating `T::new()` in favour of `Default::default()`!

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [August 18, 2021, 9:08pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195/6 "2021-08-18T21:08:35Z")

</div>

Context Soni omitted (_please_ try to provide more context rather than assuming people have the full context you do): they maintain this crate:

[https://crates.io/crates/impl\_trait](https://crates.io/crates/impl_trait)

> TL;DR: this adds `impl_trait!` which lets you do:
> 
> ```rust
> struct Foo;
> 
> trait Bar {}
> 
> impl_trait! {
> /// Yes, you can write docs here.
> impl Foo {
> /// You can write docs here too.
> fn as_dyn_bar(&self) -> &dyn Bar {
> self
> }
> /// You can even write docs here!
> impl trait Bar {
> }
> }
> }
> 
> ```

---

<div class="post-metadata">

**Author:** ![Soni](https://avatars.discourse-cdn.com/v4/letter/s/a3d4f5/32.png) [@Soni](https://internals.rust-lang.org/u/Soni)\
**Post date:** [August 18, 2021, 9:12pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195/7 "2021-08-18T21:12:46Z")

</div>

> [@Soni](#):
>
> our crate

.

* * *

we actually did provide context, altho you may have missed it. anyway we're too sleep deprived for this so gl.

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [August 18, 2021, 9:20pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195/8 "2021-08-18T21:20:42Z")

</div>

> **Manually hidden reply**
>
> You referenced it without introducing what it was. Thus, a reader not already familiar with the `impl_trait` crate lacks context. Providing a link on "our crate" would at least allow said reader to discover said context, where currently there is no context for what `impl_trait!` even does.
> 
> In any case, this is wildly off topic, and I'll stop going off topic to try to help you improve your posts.

---

<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:** [November 16, 2021, 9:20pm UTC](https://internals.rust-lang.org/t/a-shorthand-for-implementing-traits/15195/9 "2021-11-16T21:20:51Z")

</div>

Closed on November 16, 2021, 9:20pm UTC

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