Closed
Description
Going through the Rust book on the Returning Closures section, I found the code suddenly switches the factory function from using Vec<i32>
to i32
and without explanation
fn factory() -> (Fn(i32) -> Vec<i32>) {
let vec = vec![1, 2, 3];
|n| vec.push(n)
}
...
fn factory() -> &(Fn(i32) -> Vec<i32>) {
let vec = vec![1, 2, 3];
|n| vec.push(n)
}
let f = factory();
let answer = f(4);
assert_eq!(vec![1, 2, 3, 4], answer);
But we get another error:
error: missing lifetime specifier [E0106]
fn factory() -> &(Fn(i32) -> i32) {
^~~~~~~~~~~~~~~~~
Right. Because we have a reference, we need to give it a lifetime. But our factory() function takes no arguments, so elision doesn’t kick in here. What lifetime can we choose? 'static:
fn factory() -> &'static (Fn(i32) -> i32) {
let num = 5;
|x| x + num
}
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
This caused a bit of confusion, specially when trying to use the given solution to returning closures with Vec<i32>
since using the solution throws an error with that type:
fn factory() -> Box<Fn(i32) -> Vec<i32>> {
let vec = vec![1, 2, 3];
Box::new(move |n| vec.push(n))
}
src/main.rs:44:23: 44:34 error: mismatched types:
expected `collections::vec::Vec<i32>`,
found `()`
(expected struct `collections::vec::Vec`,
found ()) [E0308]
src/main.rs:44 Box::new(move |n| vec.push(n))
^~~~~~~~~~~
error: aborting due to previous error
Could not compile `learning_rust`.
To learn more, run the command again with --verbose.
Am I missing something here or should the documentation use i32
from the beginning of the section? If there's anything I can do to help with this I'd be glad to make a PR.
Metadata
Metadata
Assignees
Labels
No labels