Skip to content

Commit 352838e

Browse files
author
Michael Rosenberg
committed
Update "Generic Functions" section
Updated sample code to updated syntax (now compiles). Also tweaked the text to reflect the change.
1 parent 90bed3f commit 352838e

File tree

1 file changed

+8
-17
lines changed

1 file changed

+8
-17
lines changed

src/doc/reference.md

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1099,40 +1099,31 @@ signature. Each type parameter must be explicitly declared, in an
10991099
angle-bracket-enclosed, comma-separated list following the function name.
11001100

11011101
```{.ignore}
1102-
fn iter<T>(seq: &[T], f: |T|) {
1103-
for elt in seq.iter() { f(elt); }
1102+
fn iter<T, F>(seq: &[T], f: F) where T: Copy, F: Fn(T) {
1103+
for elt in seq { f(*elt); }
11041104
}
1105-
fn map<T, U>(seq: &[T], f: |T| -> U) -> Vec<U> {
1105+
fn map<T, U, F>(seq: &[T], f: F) -> Vec<U> where T: Copy, U: Copy, F: Fn(T) -> U {
11061106
let mut acc = vec![];
1107-
for elt in seq.iter() { acc.push(f(elt)); }
1107+
for elt in seq { acc.push(f(*elt)); }
11081108
acc
11091109
}
11101110
```
11111111

11121112
Inside the function signature and body, the name of the type parameter can be
1113-
used as a type name.
1113+
used as a type name. [Trait](#traits) bounds can be specified for type parameters
1114+
to allow methods with that trait to be called on values of that type. This is
1115+
specified using the `where` syntax, as in the above example.
11141116

11151117
When a generic function is referenced, its type is instantiated based on the
11161118
context of the reference. For example, calling the `iter` function defined
11171119
above on `[1, 2]` will instantiate type parameter `T` with `i32`, and require
1118-
the closure parameter to have type `fn(i32)`.
1120+
the closure parameter to have type `Fn(i32)`.
11191121

11201122
The type parameters can also be explicitly supplied in a trailing
11211123
[path](#paths) component after the function name. This might be necessary if
11221124
there is not sufficient context to determine the type parameters. For example,
11231125
`mem::size_of::<u32>() == 4`.
11241126

1125-
Since a parameter type is opaque to the generic function, the set of operations
1126-
that can be performed on it is limited. Values of parameter type can only be
1127-
moved, not copied.
1128-
1129-
```
1130-
fn id<T>(x: T) -> T { x }
1131-
```
1132-
1133-
Similarly, [trait](#traits) bounds can be specified for type parameters to
1134-
allow methods with that trait to be called on values of that type.
1135-
11361127
#### Unsafety
11371128

11381129
Unsafe operations are those that potentially violate the memory-safety

0 commit comments

Comments
 (0)