147 points · by ciprian_craciun · 4y ago · 107 comments
Sure, the performance characteristics could be improved, but other than that they solve all my main pain points I wanted them to solve while being constrained enough to not result in ivory towers on every corner.
My main pain points having been duplicated functions for each type as well as data structures.
In the meantime I guess there's always anonymous functions (to use as accessors). They're not hard to be generic over.
You can easily and cleanly work around this by exposing getter and setter method in your interface.
Rust is the same I think, where you'd need to have methods that explicitly implement the trait (interface in Go). However, Rust has a built-in code generation tool (macros), and you can decorate your structs to have it automatically implement some traits for you. That's the equivalent of adding one more entry to your Go generated code loop, except that it's right next to the struct.
If Go did support field methods (which it looks like they may one day), that might be the tipping point for me for disabling a bunch of generated code. Not sure if there's other things getting in my way, because I gave up once I noticed I couldn't do that.
BTW, accessing common fields is temporarily disabled before releasing Go 1.18, because there is another fundamental problem which needs to be resolved firstly.
Rich Hickey's talks can be very insightful in this regard. He surely convinced me :)
On the other extreme, you have Rust and Haskell type systems where you spend gratuitous time on pacifying the type checker for negligible quality gains (arguably negative gains).
I always felt Go hit the sweet spot.
It's easy to confuse type systems with correctness or clarity of thought. I've fallen victim to this myself – "oh this didn't map well to Rust's type system, I must be thinking wrong", kinda. It tickles this ocd nerve and I lose focus on the problem I'm trying to solve, often without realizing that I'm just wasting time.
I also like Go for these reasons. It's dumb and predictable, which let's me focus on the problem I'm solving. My only annoyance is really verbosity and small amounts of boilerplate.
When programming in the large, type systems are flat out an unmitigated win. The more you can confidently assert about your program before run time, the more time and money your team will save. If you are programming a large system and not using strong static typing, optimally with higher-level features like parametric types, then you are doing it wrong.
In the early stages of developing something complex you often want to play fast and loose with the type system - get some code running, and some tests set up, and go from there. But later on you want to refine it and start catching some more errors statically.
The pendulum has swung really far to static typing - and I get why. But if it swings back I hope we don't forget about gradual typing.
I'm not kidding. Go is at a very nice verbosity level as far as reading code goes, but writing it is indeed tedious occasionally. However, in practice, Copilot is able to handle those bits extremely well, giving us the best of both worlds.
1) The failure of
func (t *fishTank) fishCount() string {
return fmt.Sprintf("How many fishies? %d!", t.size())
}
to work has nothing to do with generics; methods are always "removed" from types defined this way. If you want you can cast `t` to a `*container[fish]` and call it, but this is also where I would ask why "extend" rather than compose - are you gaining anything by ensuring identical layouts?2) The bigger issue, that interfaces cannot require their implementations to be comparable, is https://github.com/golang/go/issues/52614 and linked tickets.
1) is totally generics unrelated.
package main
type T1 int
func (T1) M() {}
type T2 T1
func main() {
var t2 T2
t2.M() // t2.M undefined
}
The fishTank should be defined as type fishTank struct {
container[fish]
}
instead.2) is a temporary restriction, among many in the Go 1.18. Some of the restrictions will be removed from future Go versions.
ref:
* https://go101.org/generics/101.html
* https://github.com/golang/go/issues/50646#issuecomment-10237...
* https://github.com/golang/go/issues/51257
* https://github.com/golang/go/issues/51338
* https://github.com/golang/go/issues/52474
* https://github.com/golang/go/issues/52509
(Vs. e.g re-enabling better type inference where the goal is known and it's "just" implementation work.)
See: https://go.dev/doc/faq#inheritance and https://go.dev/doc/effective_go#embedding
It’s a little confusing because for primitive operations, it kind of looks like Go has inheritance, but this isn’t true for user-defined methods. (And automatic casting might in some cases compound the confusion.)
data T1 = T1 Int
m :: T1 -> ()
m t = ()
newtype T2 = T2 T1
main :: IO ()
main =
let t2 = T2 (T1 23)
v = m t2
in return ()
Gets: main.hs:11:15: error:
\* Couldn't match expected type `T1' with actual type `T2'
\* In the first argument of `m', namely `t2'
In the expression: m t2
In an equation for `v': v = m t2
|
11 | v = m t2
| ^^There may be some discussions about this, hidden in the go-nuts forum. But I don't know how to filter them out.
But a `fishTank` is not a `container[fish]`.
In common parlance
type T Thing
is newtyping. T has the same implementation as the underlying type, and Go allows conversions back and forth, but they are otherwise unrelated, and the new type does not share the interface (method set) of the original.It is, in a way, a shorthand for
type T struct { _0 Thing } $ ghci
GHCi, version 8.8.4: https://www.haskell.org/ghc/ :? for help
Prelude> class HasField a where { field1 :: a -> Int }
Prelude> data Foo = Foo
Prelude> instance HasField Foo where { field1 f = 2 }
Prelude> field1 Foo
2
Prelude> newtype Bar = Bar Foo
Prelude> :t Bar
Bar :: Foo -> Bar
Prelude> field1 (Bar Foo)
<interactive>:7:1: error:
• No instance for (HasField Bar) arising from a use of
‘field1’
• In the expression: field1 (Bar Foo)
In an equation for ‘it’: it = field1 (Bar Foo)
Prelude> type Baz = Foo
Prelude> field1 (Foo :: Baz)
2https://go.dev/play/p/GrLYBj3N0jr
The trick is to define the fish tank like so:
type fishTank struct {
container[fish]
} func (t *fishTank) fishCount() string {
return fmt.Sprintf("How many fishies? %d!", (*container[fish])(t).size())
}
that's because type fishTank container[fish]
creates a completely new and independent type with container[fish] as the underlying implementation.An alternative is to just alias:
type fishTank = container[fish]
however in that case you can't define methods on fishTank, because it's literally just a shorthand for container[fish].Another disappointing thing is the fact that Go type inference is not good enough to have syntactically compact lambda functions. So now, even though it's possible to write code that does filter-map-reduce kind of stuff, it's verbose, slow to write and hard to read.
Go is going to be torn between the minimalism of its creators, and the desires for modern capabilities expressed by its vocal user base. If this were a movie, it would be "A Beautiful Mind".
But I think there are also people who appreciate stability? It’s a language people complain about in part because it’s popular.
In this case, Tim Bray tripped over “Go doesn’t have inheritance, but it does have embedding” and ran into a couple limitations in the first version of generics, but he’s not making any wider claims.
> Among the 26% of respondents who said Go lacks language features they need, 88% selected generics as a critical missing feature.
From https://go.dev/blog/survey2020-results
Most folks I work with are among the 74% who are content with the language and are mostly cautious of the complexity associated with generics.
// --- There's no int min() in stdlib -----------------------------------------
// Option 1. use math.Min() which is defined for float64, benchmarks comparing this with Option 2 & 3:
// BenchmarkMinImplementations/math.Min-8 261596238 4.282 ns/op
// BenchmarkMinImplementations/minGeneric-8 588252955 2.037 ns/op
// BenchmarkMinImplementations/minVariadic-8 413756245 2.827 ns/op
// Option 2. Generics in Go 1.18, this is generic over int and float but can't support a variadic "b"
func minGeneric[T constraints.Ordered](a, b T) T {
if a < b {
return a
}
return b
}
// Option 3. I was aiming for a lisp-style (min 1 2.3 -4) and this is variadic but it can't also be generic in 1.18
func minIntVariadic(a int, bs ...int) int {
for _, b := range bs {
if b < a {
a = b
}
}
return a
}
Coming from Java there's less to get your head around, e.g. super vs. extends isn't a thing here but otherwise similar.(I'm aware it's not actually using the varargs reasonably, typing code on a phone is a pain)
Are you learning Go with a familiar project? or is there another motivation for Quamina?
Go is a kitchen full of dull knives. It is good for layers of communication where you call other microservices to perform the heavy lifting, but not much else.
In most cases it doesn't have "poor" performance and if you're going for optimal performance you are almost never going to be using generic data structures anyways because there's almost always type specific optimizations that can be done.
The intended use case is, and always has been, decently performing type safe data structures and Go generics are sufficient in most cases for that. Go is never going to be a functional programming language.
I imagine there's a rationale for not implementing generics this way, like keeping binaries small, but it seems like a weird tradeoff considering it increases overall memory consumption and decreases performance quite a lot...
This is not valid code.