I was experimenting with function pointer magic in Rust and ended up with a code snippet which I have absolutely no explanation for why it compiles and even more, why it runs.>
Although this is entirely up to UB, here's what I assume might be happening in the two cases:
The type F
is a closure with no data. This is equivalent to a function, which means that F
is a function item. What this means is that the compiler can optimize any call to an F
into a call to whatever function produced F
(without ever making a function pointer). See this for an example of the different names for these things.
The compiler sees that val
is always 42, and hence it can optimize it into a constant. If that's the case, then the closure passed into create
is again a closure with no captured items, and hence we can follow the ideas in #1.
Additionally, I say this is UB, however please note something critical about UB: If you invoke UB and the compiler takes advantage of it in an unexpected way, it is not trying to mess you up, it is trying to optimize your code. UB after all, is about the compiler mis-optimizing things because you've broken some expectations it has. It is hence, completely logical that the compiler optimizes this way. It would also be completely logical that the compiler doesn't optimize this way and instead takes advantage of the UB.