Cast usize to fn()?

Can't figure out how to case usize to fn().

let handler = some_usize_var as fn();
// Compiler Output:
// error: non-scalar cast: 'usize' as 'fn()'

Why?

I'm trying to use the mio library, but instead of passing a usize to the Token type, I'd like to pass a function pointer. When the Handler pops, I'd like it to take the token and cast it back to a function ponter so I can call it.

You can only do true casts using the as operator. Here's a list of true casts. You can do what you're trying to do using transmute.

2 Likes

There are some gotchas with transmuting fns: https://github.com/rust-lang/rust/issues/19925

2 Likes