Portable function pointer in Rust

I'm translating a python program into Rust
in python

 _parse_funcs: Dict[Any, Callable] = {
        str: lambda token: token,
        int: lambda token: int(token),
        float: lambda token: float(token)
        # TODO: tag -> User/Channel/Role...

How to translate it into Rust?

Mainly is the question of Callable

I don't think this can be directly translated. All three functions in that dict have different return types, which means they cannot be used interchangeably in Rust. Maybe if you provide a broader context in which this is used, we can find an appropriate solution. Currently, this sounds a little like an XY-Problem to me.

For an in-depth guide to function types in Rust, there's this excellent video.

1 Like

You can have an enum with three function pointer variants, I have this enum which may be similar to what you need:

pub enum CompileFunc {
    Value(fn(_: &Block<'_>, _: &mut [Expr]) -> CExpPtr<Value>),
    Int(fn(_: &Block<'_>, _: &mut [Expr]) -> CExpPtr<i64>),
    Float(fn(_: &Block<'_>, _: &mut [Expr]) -> CExpPtr<f64>),

The right solution depends on what functionality you actually need.

If all you need is to pick a function based on the expected type of something, then a match over a plain enum may be sufficient. The match would need to resolve to the same type at the end. One way that could work is to modify the structure that is being parsed into directly instead of returning the value.

If you need to swap out the functions at runtime, then multiple instances of a struct type with fn pointer fields and the above match statement may be enough.

If you really need all the functionality of a map of types to functions, you can use the anymap crate. But I would encourage you to use a simpler way if you can.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.