Skip to content

Commit 7799a79

Browse files
committed
TRPL: type aliases and unsized types
1 parent 3860240 commit 7799a79

File tree

2 files changed

+85
-2
lines changed

2 files changed

+85
-2
lines changed

src/doc/trpl/type-aliases.md

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,55 @@
11
% `type` Aliases
22

3-
Coming soon
3+
The `type` keyword lets you declare an alias of another type:
4+
5+
```rust
6+
type Name = String;
7+
```
8+
9+
You can then use this type as if it were a real type:
10+
11+
```rust
12+
type Name = String;
13+
14+
let x: Name = "Hello".to_string();
15+
```
16+
17+
Note, however, that this is an _alias_, not a new type entirely. In other
18+
words, because Rust is strongly typed, you’d expect a comparison between two
19+
different types to fail:
20+
21+
```rust,ignore
22+
let x: i32 = 5;
23+
let y: i64 = 5;
24+
25+
if x == y {
26+
// ...
27+
}
28+
```
29+
30+
this gives
31+
32+
```text
33+
error: mismatched types:
34+
expected `i32`,
35+
found `i64`
36+
(expected i32,
37+
found i64) [E0308]
38+
if x == y {
39+
^
40+
```
41+
42+
But, if we had an alias:
43+
44+
```rust
45+
type Num = i32;
46+
47+
let x: i32 = 5;
48+
let y: Num = 5;
49+
50+
if x == y {
51+
// ...
52+
}
53+
```
54+
55+
This compiles without error. `Num` types are the same as `i32`s, in every way.

src/doc/trpl/unsized-types.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,34 @@
11
% Unsized Types
22

3-
Coming Soon!
3+
Most types have a particular size, in bytes, that is knowable at compile time.
4+
For example, an `i32` is thirty-two bits big, or four bytes. However, there are
5+
some types which are useful to express, but do not have a defined size. These are
6+
called ‘unsized’ or ‘dynamically sized’ types. One example is `[T]`. This type
7+
represents a certain number of `T` in sequence. But we don’t know how many
8+
there are, so the size is not known.
9+
10+
Rust understands a few of these types, but they have some restrictions. There
11+
are three:
12+
13+
1. We can only manipulate an instance of an unsized type via a pointer. An
14+
`&[T]` works just fine, but a `[T]` doesn’t.
15+
2. Variables and arguments cannot have dynamically sized types.
16+
3. Only the last field in a `struct` may have a dynamically sized type; the
17+
other fields must not. Enum varants must not have dynamically sized types as
18+
data.
19+
20+
# ?Sized
21+
22+
If you want to write a function that accepts a dynamically sized type, you
23+
can use the special bound, `?Sized`:
24+
25+
```rust
26+
struct Foo<T: ?Sized> {
27+
f: T,
28+
}
29+
```
30+
31+
This `?` means that this bound is special: it lets us match more kinds, not
32+
less. It’s almost like every `T` implicitly has `T: Sized`, and the `?` undoes
33+
this default.
34+

0 commit comments

Comments
 (0)