Simple query from Book 5.3 [Functions]


#1

From the book 5.3 [Functions]
This is obvious:

fn foo(x: i32) -> i32 { x }

Which I read as: a Function foo, takes an x that is type i32 and returns and type i32 output.

I’m struggling then to make this plain English:

let x: fn(i32) -> i32 = foo;

What does “x: fn(i32)” suggest ?


#2

You’re parsing it wrong. I’ll use <[ and ]> for grouping:

let <[ x ]> : <[ fn(i32) -> i32 ]> = <[ foo ]> ;

That is, it defines a binding to x of type fn(i32) -> i32, initialised to foo. All you’re doing is storing the foo function pointer into a variable x.


#3

As a different way of putting things (in conjunction with @DanielKeep’s post):

In let x: fn(i32) -> i32 = foo;, fn(i32) -> i32 is the type of x.

fn(i32) -> i32 is syntax that represents the “type” of a function - something which you can then call later, but is stored in a variable x rather than in a named function. By using let x: fn(i32) -> i32 = ..., we are setting x to be a variable representing a function - in this specific case, x is now a pointer to the function foo.


#4

Thanks, those are both very helpful replies.

I’m expecting that is more exactly “in the case i32”. So:

x is now a pointer to the function foo, in the case i32.

I’m expecting then another could be suggested as
let y: fn(i64) -> i64 = foo;

I just discovered Rust’s Grammar, which is also helping too, though just as it was getting especially interesting, it declares FIXMEs… I was hoping to draw more sense from 6.1.3.1 Generic functions but I expect that will come in time.

:+1: