←back to thread

Constraints in Go

(bitfieldconsulting.com)
210 points gus_leonel | 1 comments | | HN request time: 0.208s | source
Show context
indulona ◴[] No.42163167[source]
i have been writing Go exclusively for 5+ years and to this day i use generics only in a dedicated library that works with arrays(slices in Go world) and provides basic functionality like pop, push, shift, reverse, filter and so on.

Other than that, generics have not really solved an actual problem for me in the real world. Nice to have, but too mush fuss about nothing relevant.

replies(10): >>42163189 #>>42163244 #>>42163415 #>>42163694 #>>42163834 #>>42164296 #>>42164983 #>>42165141 #>>42165270 #>>42165680 #
kgeist ◴[] No.42163244[source]
Just checked, in my current project, the only place where I use generics is in a custom cache implementation. From my experience in C#, generics are mostly useful for implementing custom containers. It's nice to have a clean interface which doesn't force users to cast types from any.
replies(3): >>42163435 #>>42163970 #>>42164712 #
1. BlackFly ◴[] No.42163435[source]
Containers are sort of the leading order use of generics: I put something in and want to statically get that type back (so no cast, still safe).

Second use I usually find is when I have some structs with some behavior and some associated but parameterizable helper. In my case, differential equations together with guess initializers for those differential equations. You can certainly do it without generics, but then the initial guess can be the wrong shape if you copy paste and don't change the bits accordingly. The differential equation solver can then take equations that are parameterized by a solution type (varying in dimension, discretisation and variables) together with an initializer that produces an initial guess of that shape.

Finally, when your language can do a bit of introspection on the type or the type may have static methods or you have type classes, you can use the generic to control the output.

Basically, they are useful (like the article implies) when you want to statically enforce constraints. Some people prefer implicitly enforcing the constraint (if the code works the constraint is satisfied) or with tests (if the tests pass the constraint is satisfied). Other people prefer to have the constraints impossible to not satisfy.