Skip to content

Commit

Permalink
trpl: move tuple-structs.md into structs.md
Browse files Browse the repository at this point in the history
  • Loading branch information
geofft committed May 13, 2015
1 parent 2a5a320 commit 457aed7
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 61 deletions.
1 change: 0 additions & 1 deletion src/doc/trpl/SUMMARY.md
Expand Up @@ -43,7 +43,6 @@
* [Universal Function Call Syntax](ufcs.md)
* [Crates and Modules](crates-and-modules.md)
* [`const` and `static`](const-and-static.md)
* [Tuple Structs](tuple-structs.md)
* [Attributes](attributes.md)
* [`type` aliases](type-aliases.md)
* [Casting between types](casting-between-types.md)
Expand Down
60 changes: 60 additions & 0 deletions src/doc/trpl/structs.md
Expand Up @@ -117,3 +117,63 @@ ones, and it will copy the values you don’t specify:
let origin = Point3d { x: 0, y: 0, z: 0 };
let point = Point3d { z: 1, x: 2, .. origin };
```

# Tuple structs

Rust has another data type that’s like a hybrid between a [tuple][tuple] and a
struct, called a ‘tuple struct’. Tuple structs have a name, but
their fields don’t:

```rust
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
```

[tuple]: primitive-types.html#tuples

These two will not be equal, even if they have the same values:

```rust
# struct Color(i32, i32, i32);
# struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
```

It is almost always better to use a struct than a tuple struct. We would write
`Color` and `Point` like this instead:

```rust
struct Color {
red: i32,
blue: i32,
green: i32,
}

struct Point {
x: i32,
y: i32,
z: i32,
}
```

Now, we have actual names, rather than positions. Good names are important,
and with a struct, we have actual names.

There _is_ one case when a tuple struct is very useful, though, and that’s a
tuple struct with only one element. We call this the ‘newtype’ pattern, because
it allows you to create a new type, distinct from that of its contained value
and expressing its own semantic meaning:

```rust
struct Inches(i32);

let length = Inches(10);

let Inches(integer_length) = length;
println!("length is {} inches", integer_length);

This comment has been minimized.

Copy link
@klingtnet

klingtnet Jun 19, 2015

Contributor

Why is the example introducing the integer_length variable? Instead one could have written println!("length is {} inches", length.0); or if you want the integer_length variable, why not declare it using the tuple indexing: let integer_length = length.0;?

```

As you can see here, you can extract the inner integer type through a
destructuring `let`, just as with regular tuples. In this case, the
`let Inches(integer_length)` assigns `10` to `integer_length`.
60 changes: 0 additions & 60 deletions src/doc/trpl/tuple-structs.md

This file was deleted.

0 comments on commit 457aed7

Please sign in to comment.