I think there are 3 issues with this specific subsection:
The complier error is out of date. The new complier error is better as it better reflects what I understand to be "best practices" (see issue 2).
Add a note that is better to return an impl Trait instead of a (boxed or otherwise referenced) dyn Trait if possible (i.e. when all returned values are the same type). This is better as it avoids the run-time performance penalties of using a trait object. From the reference.
The line:
you’re not allowed to use the function pointer fn as a return type, for example.
Is flat out incorrect. The following code does compile:
fn add_one(x: i32) -> i32 {
x + 1
}
//function pointer as return type is actually fine!
fn return_func(specify: i32) -> fn(i32) -> i32
{
match specify{
1 => add_one,
_ => panic!("PANIC")
}
}
fn main() {
let a = return_func(1);
println!("add_one(1) is {}", a(1));//prints add_one(1) is 2
}
In fact, in some cases you can coerce closures to function pointers:
fn returns_closure() -> fn(i32) -> i32 {
|x| x + 1
}
fn main() {
let a = returns_closure();
println!("add_one(1) is {}", a(1));//prints add_one(1) is 2
}
I think there are 3 issues with this specific subsection:
The complier error is out of date. The new complier error is better as it better reflects what I understand to be "best practices" (see issue 2).
Add a note that is better to return an
impl Trait
instead of a (boxed or otherwise referenced)dyn Trait
if possible (i.e. when all returned values are the same type). This is better as it avoids the run-time performance penalties of using a trait object. From the reference.The line:
Is flat out incorrect. The following code does compile:
In fact, in some cases you can coerce closures to function pointers: