File tree 2 files changed +60
-0
lines changed
2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change @@ -316,6 +316,35 @@ assert_eq!(3, answer);
316
316
Now we take a trait object, a ` &Fn ` . And we have to make a reference
317
317
to our closure when we pass it to ` call_with_one ` , so we use ` &|| ` .
318
318
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
+
319
348
# Returning closures
320
349
321
350
It’s very common for functional-style code to return closures in various
Original file line number Diff line number Diff line change @@ -227,3 +227,34 @@ as any type:
227
227
let x: i32 = diverges();
228
228
let x: String = diverges();
229
229
```
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
+ ```
You can’t perform that action at this time.
0 commit comments