How to create HashMap<String, Any> in struct

pub struct fsconstants {
    pub tokio_runtime: Runtime,
    pub properties: HashMap<String, dyn Any>,
}

I want to hold any data type inside hashmap. It could be another struct/ another hashmap / string --which will be known only in run time. However the above gives error

A trait to emulate dynamic typing.

Most types implement Any. However, any type which contains a non-'static reference does not. See the module-level

how to fix the issue? any thoughts?

First of all, what to you want to do with this data? You might want to find a less generic, but more ergonomic (and probably more performant) way by explicitly communicating your expectations to the compiler.

As for the current question, here's the error you are probably expected to be seeing, instead of whatever is shown by your IDE:

error[E0277]: the size for values of type `(dyn Any + 'static)` cannot be known at compilation time
 --> src/lib.rs:6:21
  |
6 |     pub properties: HashMap<String, dyn Any>,
  |                     ^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `(dyn Any + 'static)`
note: required by a bound in `HashMap`
 --> /rustc/9eb3afe9ebe9c7d2b84b71002d44f4a0edac95e0/library/std/src/collections/hash/map.rs:214:1

Is there anything unclear in it?

1 Like

i want to fix it?

Essentially i want to maintain centralised constants like we do in java

class{
    public static final Map<String,Object> map = new HashMap<String,Object>();
}

The closest i could achieve is Any keyword in a struct. But then i get into this above issue.

I don't know the size of the map ahead in time.

Trait objects need to be behind some kind of indirection. The simplest solution here would be to use Box<dyn Any>.

In Java objects are implicitly allocated individually, so storing an Object consists of just storing a pointer. In Rust types are stored directly by default, so you have to opt in to the individual allocation.

1 Like

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.