by stouset · 1y ago · 0 comments
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?
It's static vs. dynamic and strong vs. weak.
Okay... but the reply was to the parent who questioned if the typing is static. It is by way of structural typing. The compiler enforces that the ducks, so to speak, are compatible. But as an empty interface has no constraints, all types are compatible. Whatever some other comment was talking about is irrelevant.
> but about sync.Pool type erasing
The type isn't erased...?
p := sync.Pool{New: func() interface{} { return 1 }}
fmt.Printf("%T", p.Get()) // Prints: int
> So you can put (and will retrieve) random garbage from it.And you think that makes it dynamically typed? It does not.
Go is pretty strict about breaking changes, so they probably won't change the current implementations; maybe we'll see a v2 version, or maybe not. The more code you have, the more code you have to maintain, and given Go's backward-compatibility promises, that's a lot of work.
That’s not a strong argument. You can easily (but sometimes tediously) wrap any API with one that (further) restricts what types you can use with it. Generics make it possible to avoid doing that work, and code you don’t write won’t have errors.
From the Godoc:
> The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a Map may significantly reduce lock contention compared to a Go map paired with a separate Mutex or RWMutex.
Source: https://pkg.go.dev/sync#Map
And regarding slow writes, those were recently improved in Go 1.24:
> The implementation of sync.Map has been changed, improving performance, particularly for map modifications. For instance, modifications of disjoint sets of keys are much less likely to contend on larger maps, and there is no longer any ramp-up time required to achieve low-contention loads from the map.
Source: https://go.dev/doc/go1.24#minor_library_changes ("sync" section)
It serves as a way around a limitation in the type system which you don't want to deal with.
You can still have the rest of the code base be safe, as long as you create a wrapper which is.
The same can be said about having imperative implementations with functional interfaces wrapping said implementation. From the outside, you have a view of a system which is functionally sound. Internally, it might break the rules and use imperative code (usually for the case of efficiency).
Go’s type system has your back when you’re writing easy stuff.
But it throws up its hands and leaves you to fend for yourself when you need to do nearly anything interesting or complex, which is precisely when I want the type system to have my back.
I should not have to worry (or worse, not worry and be caught off guard) that my pool of database connections suddenly starts handing back strings.
It's about the same as Java and C# prior to their adoption of generics, and largely for the same reasons.
> 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.
But that's only run when the pool needs to allocate more space. What GP seems to expect is that sync.Pool() would always return a zeroed structure, just as Golang allocation does.
I think Golang's implementation does make sense, as sync.Pool() is clearly an optimization you use when performance is an issue; and in that case you almost certainly want to only initialize parts of the struct that are needed. But I can see why it would be surprising.
> [any] is a type
It's typed the way Python is typed, not the way Rust or C are typed; so loses the "if it compiles there's a good chance it's correct" property that people want from statically typed languages.
I don't use sync.Pool, but it does seem like now that we have generics, having a typed pool would be better.
If that's what people actually wanted, Coq and friends would be household names, not the obscure oddities that they are. All the languages that people actually use on any kind of regular basis require you to write tests in order to gain that sense of correctness, which also ends up validating type-correctness as a natural byproduct.
"A machine can help me refactor my code" is the property that most attracts people to the statically typed languages that are normally used. With "I can write posts about it on the internet" being the secondary property of interest.
Not quite that. Imagine I have a pool of buffers with a length and capacity, say when writing code to handle receiving data from the network.
When I put one of those buffers back, I would like the next user of that buffer to get it back emptied. The capacity should stay the same, but the length should be zero.
I think it’s reasonable to have a callback to do this. One, it doesn’t force every consumer of the pool to have to remember themselves; it’s now a guarantee of the system itself. Two, it’s not much work but it does prevent me from re-emptying freshly-allocated items (in this case reinitialzing is fast, but in some cases it may not be).
This also should be an optional callback since there are many cases where you don’t want any form of object reset.
One could define a new "Pool[T]" type (extending sync.Pool) to get these guarantees:
type Pool[T any] sync.Pool // typed def
func (p *Pool[T]) Get() T { // typed Get
pp := (*sync.Pool)(p)
return pp.Get().(T)
}
func (p *Pool[T]) Put(v T) { // typed Put
pp := (*sync.Pool)(p)
pp.Put(v)
}
intpool := Pool[int]{ // alias New
New: func() any { var zz int; return zz },
}
boolpool := Pool[bool]{ // alias New
New: func() any { var zz bool; return zz },
}
https://go.dev/play/p/-WG7E-CVXHRSo long as that one is not you? You completely forgot to address the expectation:
type Foo struct{ V int }
pool := Pool[*Foo]{ // Your Pool type.
New: func() any { return new(Foo) },
}
a := pool.Get()
a.V = 10
pool.Put(a)
b := pool.Get()
fmt.Println(b.V) // Prints: 10; 0 was expected.Might be, but that's a design decision that has nothing to do with type or generics, isn't it? You seem to refer to a function to drain the pool, which is not needed, and frankly, rather unusual.
> It's typed the way Python is typed
Not in the slightest.
> "if it compiles there's a good chance it's correct"
If you want to compare it to something, it's more like Rust's unwrap(), which will panic if you apply it to the wrong result.
You know, it's this kind of comment on USENET forums which prompted the creation of StackOverflow. It's not curious and adds nothing to the discussion.
I like Go and use it extensively; and I like having the option to fall back to the `any` type. But it's simply a fact that using the `any` type means that certain properties of the program can't be checked at compile time, in the same way that Python isn't able to check certain properties of the program at compile time.
> If you want to compare it to something, it's more like Rust's unwrap(), which will panic if you apply it to the wrong result.
Rust's unwrap() is used when a type can have one of exactly two underlying types (which is why no type is specified). In this case, getting back an `any` type means the underlying type could literally be anything -- as demonstrated by the example, where they put an integer, a string, and an empty struct into the pool. That's almost certainly not what you wanted, but the compiler won't prevent you from doing it.
You make it look like it's a good thing to be able to express it.
There's no way in Java, Rust or C++ to express this, praised be the language designers.
As for expressing a pool value that may be multiple things without a horrible any type and an horrible cast, you could make an union type in Rust, or an interface in Java implemented by multiple concrete objects. Both ways would force the consumer to explicitly check the value without requiring unchecked duck typing.
That's not even the case. In Java, you'd just use Object, which is for all practical purposes equivalent to `interface{}` aka `any` in Go. And then you downcast. Indeed, code exactly like this was necessary in Java to work with collections before generics were added to the language.
In C++, there's no common supertype, but there std::any, which can contain a value of any type and be downcast if you know what the actual type is.
No, just that this pre-generics Go, and backwards compatibility is taken seriously.
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.
You might want to step off that extremely high horse for a second, buddy. It's extremely reasonable to expect a type-safe pool that only holds a single type, since that's the most common use case.