Reputation: 47
Playing around with Rust I discovered this:
How can the size of a function pointer be always the same? How do they know that the function pointer should point to a function with those specific arguments and return type then?
Upvotes: 0
Views: 510
Reputation: 58805
A function pointer is always the same size because it's a pointer! Functions defined with fn
are stored in static memory and are never moved around. A pointer is sufficient to reference them.
The arguments of the function are known at compile time, as part of the type. The type checker uses those to make sure that the function is being called correctly and to generate assembly instructions to actually call the function. At runtime, the fn
pointer can be considered to be data, while the detailed information about the function arguments is encoded in the compiled instructions.
Upvotes: 3