Skip to content

Commit e4c229b

Browse files
committed
Add more infor about function pointers to TRPL
1. mention them in the function chapter 2. mention their coercion to closures in the closures chapter Fixes #26746
1 parent d034561 commit e4c229b

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/doc/trpl/closures.md

+29
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,35 @@ assert_eq!(3, answer);
316316
Now we take a trait object, a `&Fn`. And we have to make a reference
317317
to our closure when we pass it to `call_with_one`, so we use `&||`.
318318

319+
# Function pointers and closures
320+
321+
A function pointer is kind of like a closure that has no environment. As such,
322+
you can pass a function pointer to any function expecting a closure argument,
323+
and it will work:
324+
325+
```rust
326+
fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
327+
some_closure(1)
328+
}
329+
330+
fn add_one(i: i32) -> i32 {
331+
i + 1
332+
}
333+
334+
let f = add_one;
335+
336+
let answer = call_with_one(&f);
337+
338+
assert_eq!(2, answer);
339+
```
340+
341+
In this example, we don’t strictly need the intermediate variable `f`,
342+
the name of the function works just fine too:
343+
344+
```ignore
345+
let answer = call_with_one(&add_one);
346+
```
347+
319348
# Returning closures
320349

321350
It’s very common for functional-style code to return closures in various

src/doc/trpl/functions.md

+31
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,34 @@ as any type:
227227
let x: i32 = diverges();
228228
let x: String = diverges();
229229
```
230+
231+
## Function pointers
232+
233+
We can also create variable bindings which point to functions:
234+
235+
```rust
236+
let f: fn(i32) -> i32;
237+
```
238+
239+
`f` is a variable binding which points to a function that takes an `i32` as
240+
an argument and returns an `i32`. For example:
241+
242+
```rust
243+
fn plus_one(i: i32) -> i32 {
244+
i + 1
245+
}
246+
247+
// without type inference
248+
let f: fn(i32) -> i32 = plus_one;
249+
250+
// with type inference
251+
let f = plus_one;
252+
```
253+
254+
We can then use `f` to call the function:
255+
256+
```rust
257+
# fn plus_one(i: i32) -> i32 { i + 1 }
258+
# let f = plus_one;
259+
let six = f(5);
260+
```

0 commit comments

Comments
 (0)