#static map string -> struct method

13 messages · Page 1 of 1 (latest)

fading charm
#

Having some trouble mapping a string to a mutable struct method, and putting it in static memory.

What I'd essentially like to do is:

static dict: HashMap<&str, dyn FnMut(&mut Foo, &mut Bar, &[&str])> = {
    let m = HashMap::new();
    m.insert("ping", |foo, bar, args| {
        // ...
    });
};

(this blows up with an undecipherable compiler hint)

I'd like this in either static or const memory, I'm not entirely sure the difference in Rust. This dictionary is a constant though, it will never change, and it's pointless to have one per class as a struct var.

Can anyone help me get this to work?

faint ginkgo
#

either static or const memory, I'm not entirely sure the difference in Rust
a const has its value inserted into each use, while a static is created in memory one time and references each time the binding is used

#

(this blows up with an undecipherable compiler hint)
ferrisHmm

#

-errors

vague hollowBOT
#

Run cargo check in a terminal

Note: If using rust analyzer you can click the "click for full compiler diagnostic" link in your editor.

Please post the full output of the above command, including the error title and any help or notes. An example of how this looks is:

error[E0308]: mismatched types
 --> src/main.rs:3:17
  |
3 | let foo: &i32 = bar;
  |          ----   ^^^ expected `&i32`, found integer
  |          |
  |          expected due to this
  |
help: consider borrowing here
  |
3 | let foo: &i32 = &bar;
  |                 +

When posting the error put it in a code block so it has nice formatting:

```rust
// error from cargo check here
```

Please do not post a screenshot. If the output is too long then use a paste tool like https://paste.rs/web

fading charm
#

so const is more of a macro

faint ginkgo
#

a couple things that I do see right now are:

  • you can't store a dyn Fn(...) -> _ directly, since it isn't Sized
  • you can't create a new HashMap (or insert values into one) in a const context
#

if you want a static map, you need to either use a separate crate that does that (like phf) or put the map into a LazyLock

fading charm
#

hmm, thats kind of disappointing

#

seems like theres a bunch of stuff with static variables needing to implement some thread safety too

#

i'll probably just instantiate a map with each struct and leave a TODO lol

faint ginkgo
#

yes, statics have to be Sync, since they can be accessed in multiple threads in parallel

faint ginkgo