←back to thread

480 points jedeusus | 1 comments | | HN request time: 0s | source
Show context
stouset ◴[] No.43543575[source]
Checking out the first example—object pools—I was initially blown away that this is not only possible but it produces no warnings of any kind:

    pool := sync.Pool{
        New: func() any { return 42 }
    }

    a := pool.Get()

    pool.Put("hello")
    pool.Put(struct{}{})

    b := pool.Get()
    c := pool.Get()
    d := pool.Get()

    fmt.Println(a, b, c, d)
Of course, the answer is that this API existed before generics so it just takes and returns `any` (née `interface{}`). It just feels as though golang might be strongly typed in principle, but in practice there are APIs left and rigth that escape out of the type system and lose all of the actual benefits of having it in the first place.

Is a type system all that helpful if you have to keep turning it off any time you want to do something even slightly interesting?

Also I can't help but notice that there's no API to reset values to some initialized default. Shouldn't there be some sort of (perhaps optional) `Clear` callback that resets values back to a sane default, rather than forcing every caller to remember to do so themselves?

replies(5): >>43543875 #>>43544042 #>>43544109 #>>43544700 #>>43546668 #
tgv ◴[] No.43543875[source]
You never programmed in Go, I assume? Then you have to understand that the type of `pool.Get()` is `any`, the wildcard type in Go. It is a type, and if you want the underlying value, you have to get it out by asserting the correct type. This cannot be solved with generics. There's no way in Java, Rust or C++ to express this either, unless it is a pool for a single type, in which case Go generics indeed could handle that as well. But since Go is backwards compatible, this particular construct has to stay.

> Also I can't help but notice that there's no API to reset values to some initialized default.

That's what the New function does, isn't it?

BTW, the code you posted isn't syntactically correct. It needs a comma on the second line.

replies(6): >>43543989 #>>43544008 #>>43544021 #>>43544567 #>>43545116 #>>43546665 #
1. gf000 ◴[] No.43544567[source]
How is it different than pre-generic Java?

Map/List<T> etc are erased to basically an array of Objects (or a more specific supertype) at compile-time, but you can still use the non-generic version (with a warning) if you want and put any object into a map/list, and get it out as any other type, you having to cast it as the correct type.