Function pointer


I want to write a simple game in Rust (that earlier was written in C).

In C, the data type to store user information is like this:

struct user { 
    int uid;
    unsigned credits;
    int highscore;
    char name[100];
    int (*current_game) ();

This is the data type to store user information implemented in Rust:

struct User {
    uid: i32,
    credits: u32,
    highscore: i32,
    name: &'static str, 
    // current_game: function pointer

My question is what is the syntax for a function pointer in Rust?
Thank you!


Depending on your situation, it may be in your best interests to not have User store any reference to the game at all, as this seems like it could be an anti-pattern in some cases. If you are sure you need User to have a reference to Game, read on in this post. Otherwise, could you specify what exactly User and Game (whatever type current_game is) each do?


The syntax for a function pointer like int (*) (void) is fn() -> i32. If the function comes from C, then one needs to specify that it has the C ABI: extern "C" fn() -> i32.

(Whether using a function pointer is the best way to tackle this problem is another question altogether. :slight_smile: )


current_game is a pointer to different types of games, for example one game is to guess the number, other is play poker etc.

struct user retains information about a specific player, when a player had chosen another game the current_game function pointer ‘jumps’ to execute the selected game.