#InvalidIFaceAssign with assigning a struct to any or interface{}

11 messages · Page 1 of 1 (latest)

thin seal
#

I'm curious on if there's a way to have a parameter (or property) be an interface{} type, but pass a concrete type into the struct/function.

Here's an example of what I'm talking about: https://go.dev/play/p/ElslCdi6gd5

I would think that HelloRequest and HelloResponse would be of type any (or interface{}), as I'm losing specificity. Is there something about interface{} that doesn't apply to HelloRequest / HelloResponse?

Thanks!

mental gate
#

your approach assumes that methods are covariant, but in go they are invariant, which means the number of input and output parameters and the types of all of them must match exactly to implement an interface

#

which is to say, the problem isn't that HelloRequest does not implement any, it is that HelloRoute does not implement Route because HelloRequest is not identical to any

thin seal
#

Gotcha, thanks. I'm going to guess there are no workarounds to support this kind of use-case (I tried generics but also hit a wall with the type parameters showing a similar error)

mental gate
#

there isn't a workaround per se, but it's certainly possible to approach the design in a way that lets you accomplish what you want

#

in particular, using interfaces that capture the methods you actually need from a request body and response instead of any

#

like you said, i don't think generics will be especially helpful here; they can improve type safety locally, but you would need to propagate the type parameters all the way up the entire call tree, which means you need to know them ahead of time potentially starting with func main

tawdry ledge
#

The way I did this when experimenting in the past was to just make generic middleware that transform net/http requests to the special@handler

#

i.e. generic JsonPostHandler that transforms the body to the generic input value and writes the generic return value to json

#

func PostJson[TRequest any, TResponse any](f func(TRequest) (TResponse, error)) http.Handler

thin seal
#

Thanks all, I'll give your approach a shot and report back @tawdry ledge