From d67631ae46aa82c748536bdb05d6d59dc0654057 Mon Sep 17 00:00:00 2001 From: Michelle S Date: Sat, 29 Jan 2022 13:27:46 -0700 Subject: [PATCH] New blog post --- content/blog/rust-tuple-impls.md | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 content/blog/rust-tuple-impls.md diff --git a/content/blog/rust-tuple-impls.md b/content/blog/rust-tuple-impls.md new file mode 100644 index 0000000..ef55a19 --- /dev/null +++ b/content/blog/rust-tuple-impls.md @@ -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) -- 2.45.2