~alterae/alterae.srht.site

d67631ae46aa82c748536bdb05d6d59dc0654057 — Michelle S 2 years ago 6a845e1
New blog post
1 files changed, 53 insertions(+), 0 deletions(-)

A content/blog/rust-tuple-impls.md
A content/blog/rust-tuple-impls.md => content/blog/rust-tuple-impls.md +53 -0
@@ 0,0 1,53 @@
+++
title = "`impl` blocks for tuples"
description = "adding an `impl` block for a tuple in Rust"
+++

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:

```rust
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:

```rust
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)