HashMap of Heterogeneus Functions Values

#1

I’m translating a simple Lisp interpreter written in Python to Rust for learning purposes. Some part of the code involve a dictionary of heterogeneous functions -functions that take different number and type of arguments and return different types of values or no return at all- because of the dynamic “nature” of python this is straightforward.

functions = {}
functions.update({
        'car':     lambda x: x[0],
        'cdr':     lambda x: x[1:], 
})

I was trying to do something like that:

let mut env: HashMap<String, fn(Vec<Any>) -> Box<Any>> = HashMap::new();

but have compilation problems:

103 |     let mut env: HashMap<String, fn(Vec<Any>) -> Box<Any>> = HashMap::new();
    |                                                              ^^^^^^^^^^^^ doesn't have a size known at compile-time

I was wondering how can I code this in Rust in a type safe form, any clue about this?

Thanks in advance

#2

The error is about Vec<Any>. Vec needs every element to have the same size so that it can easily address nth element, but each Any could have any size.

If you change it to Vec<Box<dyn Any>> to make each element a pointer, then the Vec will know how to store them.

2 Likes