Is it possible to call struct method by string?

is it possible to call struct method by string variable?

context.request.get()

Code

let call = "get"
(context.request).(call)()

I am not sure but I am trying the way static functions work.

No, because Rust doesn't require saving out the names of all the functions into the binary the way that dynamic languages do.

If you want to do that, try making the look-up table explicitly, with something like a HashMap<String, Box<dyn Fn()>>.

The way most languages implement this sort of feature is by having a runtime which keeps track of the types and functions in your program, when when you want to do the call it'll do a lookup in some big dictionary to figure out what to do[1]. You see this a lot in JIT-ted languages like C# and Java, or languages like Python which have an interpreter.

Rust doesn't come with this sort of runtime because that would add a lot of bloat to binaries and goes against the "only pay for what you use" philosophy, it also makes interoperating with other languages quite hard because they obviously won't use the same runtime or GC. If you want to do this sort of thing you'd need to implement it yourself via structs and objects and Box<dyn Fn(...)>.


  1. I'm simplifying things here. In practice this gets really complicated because you need to know how to pass values around. Generics also make this "big dictionary of functions" a bit more complicated because you go from having a single definition for a function to a potentially infinite number.
    Memory management is also a big, potentially undecideable concern here, so you almost always need some form of garbage collector. ↩ī¸Ž

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.