7 ms·
I've ended up using at least a half dozen generic helpers in every application I've written since they were added. They've made my coding easier, more concise,
by cy_hauser 3y ago
I've ended up using at least a half dozen generic helpers in every application I've written since they were added. They've made my coding easier, more concise, and help with testing. Adding generics to Go was well-founded.
- assbuttbuttass 3y agoCan you share some examples? I personally haven't found any excuses to use generics yet, so I'm curious where other people are finding them useful
- shinies 3y agoHere is an example in the standard library: https://pkg.go.dev/slices https://pkg.go.dev/slices
- assbuttbuttass 3y agoI've used the slices package and I agree it's useful. I was wondering more about generics use in application code
- shinies 3y agoBefore the slices package you had to write those functions for all your types, it's much better now! I also like using generics for API request/response code, ex: https://go.dev/play/p/OWf9eFmg1qF https://go.dev/play/p/OWf9eFmg1qF With generics you don't need to return any/interface{} / type assert at runtime
- assbuttbuttass 3y agoHmm for this example I would be more inclined to use an output parameter rather than generics func Request(req, resp any) error { // send request (http, etc) b, err := json.Marshal(req) if err != nil { return err } log.Printf("sent request %+v - %s", req, b) // read response if err := json.Unmarshal([]byte(`{"success": false, "error": "invalid login"}`), resp); err != nil { return err } return nil } But I kind of agree it's nicer to use a return value rather than an output parameter. I'm excited to see what other new uses people come up with for generics!