`impl` blocks for tuples

adding an `impl` block for a tuple in Rust | back

a conversation with a friend lead me to wonder if it was possible to define an impl block for a tuple in rust, so I tried it out

the first attempt did not work:

fn main() {
    println("{}", (1, 2, 3).sum());
}

impl (i32, i32, i32) {
    fn sum(&self) -> i32 {
        self.0 + self.1 + self.2
    }
}

attempting to compile produced this error message:

error[E0118]: no nominal type found for inherent implementation
 --> src/main.rs:5:6
  |
5 | impl (i32, i32, i32) {
  |      ^^^^^^^^^^^^^^^ impl requires a nominal type
  |
  = note: either implement a trait on it or create a newtype to wrap it instead

For more information about this error, try `rustc --explain E0118`.

this wasn't terribly surprising - tuple types are anonymous, and it is difficult to refer to something without a name. however, what was surprising was that the following worked:

fn main() {
    println("{}", (1, 2, 3).sum());
}

// trait just to hold the method
trait MyTrait {
    fn sum(&self) -> i32;
}

impl MyTrait for (i32, i32, i32) {
    fn sum(&self) -> i32 {
        self.0 + self.1 + self.2
    }
}

i'm not entirely sure why this works while the other doesn't, but it's nice to know that it is possible to implement methods for tuples if you for some reason need that. (which you shouldn't, since if you need methods you should really be using a tuple struct or a regular struct)

if you want to try this out for yourself for whatever reason, the code can be found on the Rust Playground