How do I return a generic structure, within a struct?

I am trying to implement a structure where the user's input will call a 3rd party API and respond with a structured container wrapped around the 3rd party API's output. This was my initial idea:

Playground URL: Rust Playground

Gist URL:

But it doesn't work. I'm thinking that I need to translate the T coming out of the called "actions" into a generic structure, say a JSON and use that as the type. Is there a more idiomatic way of doing something like this in Rust?

1 Like

Is the set of types returned from the 3rd party API known a priori? If so, you could consider using an enum to represent the different types of values.

Yes the set of APIs is limited and the possible response formats will be known at compile time. Ultimately I used the serde_json::Value as the type for T. Seems to work out ok, I just have to transform the value coming out of each API into a Value type.

I am mostly curious to see if there is a more idiomatic way of handling this type of situation. I could make an enumeration of all the possible types, but having to add a new type for each API I call just feels wrong.

Thank you for the response! This is my first attempt at using Rust, going for the gusto and straight to production with it.

You can put them into a json value, but I don't know if you actually need the type to be json serialized for other reasons or you're just using it as a form of 'Any'. I also just noticed that your Action enum is already kind of capturing the different return types, although I understand that the types within each Action variant may repeat in the real usecase.

Once you get the Response with the value, what are you going to do with it?

You can also create a trait that captures the behavior of all returned types, and then implement it for all the different return types. But I think the appropriate solution will depend on what you're going to do with those values.

Once that response is received it is just going to be passed along back to the user as JSON. There are repeating types within some of the 3rd party api requests and/or responses. This is sort of an internal proxy/abstraction over these services so that our internal system doesn't have to know where the information originates.