On Mon, 12 May 2025 at 00:25, Alexander Shopov <a...@kambanaria.org> wrote:
> I cannot just make *EnrichedResponse* a struct embedding > *generated.Response *and add more state because then I cannot do the > conversion from normal response to enriched. > Why does this have to be a conversion? What's the downside of having to type `r.Response` instead of `generated.Response(r)`? In fact, the former seems preferable? So here is my question - is there any way to have this state somewhere so > that the Enriched() method does not take more arguments but can be called > directly. > A method declaration in Go is quite static. Additional state can be kept > in some kind of closure but then I have no idea how to glue that closure to > the method. > > Is there any trick I am missing? > If you want your coworkers sad, and the Engineering gods angry, you can use unsafe: https://go.dev/play/p/tEJOLav360c A less evil, but still bad way, would be to store it in a global map: https://go.dev/play/p/ZHBJVCduf25 (note: I'm not sure this use of weak pointers is actually correct, I haven't used them yet). Otherwise, no. The state has to live somewhere. And really, both of these tricks are still really bad and you shouldn't do them. The best way is to respect the type system and if you want extra methods, you need a new type and if that needs extra state, that should be stored in the type. ----- > Why would I want to do this? What am I trying to achieve? > > Basically there is a lot of generated code and I want to keep > compatibility with it. > Similar to the way Go embeds wider interfaces into narrower ones I want to > be able to add methods to the generated code without having to change it. Change the code generator, and/or add additional code in an extra file. Hacking the language will cause you more pain, in the long run. > Then - whenever some code calls the *Get* method on the server - based on > the whether the returned value implements the *Enriched* interface or not > and the value it returns - I can dispatch behavior. > > Kind regards: > al_shopov > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion visit > https://groups.google.com/d/msgid/golang-nuts/bbe6bcd8-e33c-41bf-868a-e498561c3e72n%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/bbe6bcd8-e33c-41bf-868a-e498561c3e72n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion visit https://groups.google.com/d/msgid/golang-nuts/CAEkBMfFbreC-kh_MGk6t%3Db5Hth0DkffQALcQ886dOatL%3D8Oipw%40mail.gmail.com.