Getting the value of a variable from the tokio runtime

I'm making a very specialized reflection API for making a JSON object. I know how to get the name of the fields, but I'm stuck on another problem. I'm trying to use the Tokio runtime to get the value of the variable at runtime. After looking through the docs on the runtime (tokio::runtime::Runtime) Runtime in tokio::runtime - Rust I can't figure it out. Can anyone help me with this? Thanks!

Could you elaborate a little what you mean by that? I'm having trouble understanding what exactly you are trying to do. What is the value and what variable are you talking about?

For example:
Take this struct:

pub struct foo{  
    x: i32,
    s: String,
    b: Bar // another struct

would there be a way to pass bar into a function like this:

pub fn<T, S> get_value(strct: S) -> T {
   // more code here 

Edit: Skip this and read jofas's reply first. I'll leave the rest of this here for clarification in case what jofas mentions is not applicable.


Rust doesn't have any of the runtime type information, variant types, or dynamic generic instantiation you would need to be able to do this.

There are theoretically ways to get very limited versions of small parts of what you're implying here, but how you do that depends heavily on what it is you're actually trying to do. i.e. not get_value, but why you want get_value in the first place.

Also, I'm not sure what you think Tokio is for, but even if this functionality did exist, Tokio wouldn't have anything to do with it. It's a runtime for async code, not reflection.


So you want to get some sort of application state (an instance of Bar) from somewhere (in your case the tokio runtime), right? The tokio runtime does not support that kind of operation. Web servers build on top of tokio like Axum or Actix-web do, however. But be mindful that you need to register the value with the web server first, so you can't access any arbitrary Bar variables from your program. The easiest way to replicate that behaviour would be to store the Bar instance you want to retrieve at runtime as a static value in your program, i.e. inside a LazyLock.

1 Like

Bleh.... I'm using C++ instead. I was already coming from C++, so it'll still be hard, but I'm at least going to know the syntax

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.