Hands-on Rust: "Structs can also be tuples" (page 150, B2.0)

Notice that the syntax is different here. Structs can also be tuples. If you only have one piece of information to store inside a struct, you can replace the named fields with (pub type)—in this case, String. You can then access the contents of the structure just like a tuple - mystruct.0 contains the string.

Aside from less typing, what is the benefit of using this syntax? I’m guessing that it’s supported by Rust, so you’re introducing it here so that the reader is familiar with the approach?

1 Like

Oddly, I didn’t get a notification for this one and just found it in my email! Anyway - you’re exactly right. There’s no internal benefit to the syntax, I wanted to make sure it was included so that readers wouldn’t be surprised when the ran into it elsewhere.

You do sometimes find it combined with methods to provide a somewhat seamless use of types to represent units - with conversions between them. This can be extended using the repr_transparent feature ( https://doc.rust-lang.org/1.26.2/unstable-book/language-features/repr-transparent.html ) to be seamless, but that’s a bit beyond the scope of the book. Once that feature is stabilized into the main language, I think it’ll see a bit more use.

1 Like