Skip to content

collection/...: generic collection types #80590

Open
1 of 7 issues completed
Open

Description

@adonovan

Updates: including insertion-ordered maps, and specifying JSON marshaling behavior. 13 Oct 2026. -jba
Updated with the latest changes. 7 Oct 2026. -jba

Background: The Go Collections working group was formed in late 2025 with the purpose of bringing common collection data structures to the standard library, guided by the familiar Go principles of pragmatism and simplicity. Alphabetically by last name, the group consists of Jonathan Amsterdam (@jba), Alan Donovan (@adonovan), Robert Griesemer (@griesemer), Daniel Martí (@mvdan), Roger Peppe (@rogpeppe), Keith Randall (@khr), and Ian Lance Taylor (@ianlancetaylor). We’ve now reached a point where we’re ready to share our results with the community.

This issue is an umbrella for discussing several related proposals for new collections APIs for Go 1.28. It presents a high level overview of the themes, and links to the various concrete proposals and associated implementation CLs.

Go currently provides few collection types in its library, and from the outset we have emphasized the flexibility of the language’s built-in slice and map types. Of those provided, the most important is the heap, used for priority queues. Even sets are absent; they are conventionally expressed in terms of map[T]bool or map[T]struct{}. Ordered maps and sets based on binary trees are entirely absent.

Since the addition of generics in Go 1.18 and iterators in Go 1.23, it has become possible for library-defined types to achieve comparable ergonomics to built-in types, and for many common operations on slices and maps to be expressed as calls to library functions. This work seeks to add several of the more important data types to the standard library, and to establish conventions for their APIs and those of future additions.

Proposal: The proposed additions include:

  • #70471, CL 657296 (released in go1.27): hash/maphash.Hasher: a standard interface for expressing custom hash functions and equivalence relations for arbitrary data types. These may differ from the compiler-defined ones used by map[K]V, and are useful when the key type is not comparable (such as a slice or map), or when the default comparison yields the wrong result (such as for types.Type values, which need the deep comparison operation types.Identical). Its package docs include an example of its use in a Bloom filter.

  • #69559, CL 612217: golang.org/x/collection/hashed.Map[K,V]: a hash-based Map that uses the custom hash functions mentioned above.

  • #80584, CL 741160: golang.org/x/collection/hashed.Set[T]: a hash-based Set along the same lines.

  • #69230, CL 745441: golang.org/x/collection/set.Set[T]: a canonical data type for sets whose elements are comparable. It is transparently represented as map[T]struct{} and supports all the usual set operations such as Union and Intersection. It is more convenient than “legacy” sets based on map[T]bool and map[T]struct{}, and avoids ambiguity about potential false values in a map[T]bool. We expect it to become the standard set in most new Go APIs.

  • #60630: golang.org/x/collection/sorted.Map[K,V]: an ordered mapping. The current implementation uses a balanced binary tree, but nothing in the design requires that. The common Go pattern of building a map[K]V then sorting its keys performs well in most cases, but on occasion, such as when a range query is needed, other data structures perform much better.

  • #60630: golang.org/x/collection/sorted.Set[K,V]: an ordered set along the same lines.

  • #77397: golang.org/x/collection/heap.Heap: a generic binary heap API to replace the standard library's existing heap, which can be difficult to use.

  • #80194: insertion-ordered hash maps: hash maps augmented with iteration in the order in which items were inserted.

[The mapset package originally proposed has been withdrawn.]

We expect to consider additional proposals in due course, such as queues and stacks.

The initial implementations of all the proposed data structures aim to satisfy the API and asymptotic performance expectations as simply as possible. There are doubtless many opportunities for later optimizations to reduce constant factors, but they are out of scope of the proposal process.

The new packages will live in golang.org/x/exp, to give the community ample time for feedback. We hope to eventually add these packages to the standard library.

Although the standard library uses container for its data structure packages, we prefer the term “collection” to avoid confusion with the container virtualization concept from Linux.

Abstract collection constraint interfaces

Most of the methods of the new Map and Set types are not particular to any concrete representation type, but are common across all Maps and Sets. However, they are not really implementions of a common interface type because of the “binary method problem”: if each set data type S has a Union method of the form func (S) Union(S) S, then the Union methods of different set types are incompatible, so they have no common ordinary interface. To express this abstract Set type, we must use F-bounded polymorphism, or recursive constraint interfaces.

CL 761460 adds to the container package unexported abstract Collection, Set, and Map constraint interface types that permit package implementors to write abstract helper functions (such as ContainsAny, Subset, or Arbitrary) that work across a range of concrete collection, set or map types. We reproduce these interfaces below, with some brief commentary, to help give a high-level picture but they are not part of any proposal. They merely serve to guarantee conformance in tests. See the individual proposals for more detail.

// _AbstractCollection models a collection C of elements E,
// such as *hash.Map, *hash.Set, *ordered.Map, or set.Set.  
type _AbstractCollection[E any, C _AbstractCollection[E, C]] interface {  
	Clear()  
	Clone() C  
	Contains(E) bool  
	Len() int  
	String() string  
}

// _AbstractMap models a mapping M from keys K to values V,  
// such as *hash.Map or *ordered.Map.  
type _AbstractMap[K, V any, M _AbstractMap[K, V, M]] interface {  
	_AbstractCollection[K, M]

	All() iter.Seq2[K, V]  
	Delete(K) (V, bool)  
	DeleteFunc(func(K, V) bool) bool  
	Get(K) V  
	Keys() iter.Seq[K]  
	Lookup(K) (V, bool)  
	Set(K, V) (V, bool)  
	Values() iter.Seq[V]  
}

// _AbstractSet models a set S of elements E,  
// such as *hash.Set, or set.Set.  
type _AbstractSet[E any, S _AbstractSet[E, S]] interface {  
	_AbstractCollection[E, S]

	All() iter.Seq[E]  
	Delete(E) bool  
	DeleteFunc(func(E) bool) bool  
	Difference(S) S  
	DifferenceWith(S)  
	Equal(S) bool  
	Insert(E) bool  
	Intersection(S) S  
	IntersectionWith(S)  
	Intersects(S) bool  
	SymmetricDifference(S) S  
	SymmetricDifferenceWith(S)  
	Union(S) S  
	UnionWith(S)  
}

For now these abstract types are non-exported and merely serve as documentation of Go’s conventions to help ensure consistency. We do not propose to publish them yet, but may do so a later release after gaining experience with the concrete collection types. In the meantime, users can define minimal constraint types as needed, as in this example (from CL 761460) of a generic Take function over abstract sets:

// _TakeSet defines an abstraction of a set sufficient for the [Take] function.  
type _TakeSet[E any, S _TakeSet[E, S]] interface {  
	All() iter.Seq[E]  
	Delete(E) bool  
}

// Take removes and returns an arbitrary element from a set.  
// It returns zero if the set was empty.  
func Take[S _TakeSet[E, S], E any](set S) (e E, found bool) {  
	for e = range set.All() {  
		found = true  
		set.Delete(e)  
		break  
	}  
	return  
}

There is a certain arbitrariness to the set of methods included in each interface. For some data structures, a method permits a more efficient specialized implementation. But if every possible operation were added to the interface, the burden on the implementor would be unreasonable.

For instance, should the Set interface include a Subset(Set) bool method, or should Subset be written as a generic operation over abstract sets, like the Take example? Ordered sets can quickly reject a Subset test when the two operands have disjoint ranges, but even so, in the common case a Subset test is still typically O(n), so we decided to omit Subset from the interface. By contrast, we retained DeleteFunc in the Set and Map interfaces because, without it, conditionally deleting each element of a tree is asymptotically worse: O(n log n) instead of O(n).

By delaying the commitment to a particular set of methods, we can learn from practice. It may turn out that we don’t need to publish canonical constraint types at all.

JSON marshaling of collections

The collections will marshal to/unmarshal from JSON as follows:

  • Maps marshal exactly like built-in maps, including the treatment of key types. In JSON v2, hashed.Map marshaling honors the Deterministic option for maps that are not insertion-ordered, sorting keys if it is true. Insertion-ordered maps always marshal in insertion order, and sorted.Maps always marshal in sorted key order.

  • Sets marshal as JSON arrays. There is no special treatment of set elements (since JSON array elements need not be strings): they marshal just like any other Go value. The v2 Deterministic option is honored for set.Set and hashed.Set: if true, the marshaled byte slices of elements are sorted lexicographically (which may result in a different order than the same elements used as map keys). Elements marshal in sorted order for sorted.Set.

  • heap.Heap has no built-in marshaling behavior. There is no use case for marshaling a heap. JSON v2 users can install their own marshaler for heap.Heap if they wish.

Miscellaneous rationalizations

The remainder of this doc briefly notes a few of the many small design choices that led to the current set of proposals.

Methods return as much information as possible to avoid repeated lookups. For example:

  • Most mutation methods report whether they changed the size of the collection.
  • Map.Set and Map.Delete return the previous key if any, plus a boolean so that an existing key can be distinguished from the zero value.
  • Get is variant of At that provides the boolean. (At is provided for convenience of use in expressions.)

Map.Set should replace any existing entry with the same key, following the built-in map.

Unlike Sets, maps have no Equal method, because map values may be non-comparable.

The fundamental set operations (Intersects, Union, etc) are part of the Set interface to enable efficient concrete implementations across a variety of representations, even though many of these could be expressed abstractly in terms of just All, Len, and Contains, as shown in this table, at some asymptotic cost in performance:

- Union{,With}               interface{ All() iter.Seq\[E\] }  
- Intersection               interface{ All() iter.Seq\[E\]; Contains(E) bool; Len() int }  
- IntersectionWith           interface{                    Contains(E) bool }  
- Difference                 interface{ All() iter.Seq\[E\]; Contains(E) bool }  
- DifferenceWith             interface{ All() iter.Seq\[E\]; Contains(E) bool }  
- SymmetricDifference{,With} interface{ All() iter.Seq\[E\] }

Secondary operations such as Set.{Take,Arbitrary,Subset,Superset} were removed from the interface and expressed as generic operations using the abstract set interface, again at some potential cost in asymptotic performance. DeleteFunc was retained.

Set algebra operations such as Union are purely functional, returning their result as a new set. Each comes with a -With variant that mutates its left operand and returns no result. The two variants are “convenient” and “allocation efficient”, respectively. We rejected the idea of merging them into a single method based on experience with the math/big.Int API, and to avoid risks of accidental mutation or forgetting to use the result.

It is possible to define a KeySetView[M, K, V] wrapper type that satisfies the Set[K] abstraction using the key set of an underlying Map[K,V] of type M. (Inserting an element to the Set is of course meaningless and must panic.)

For symmetry, let’s consider each of the AbstractMap methods and the operations provided by the existing ‘maps’ package:

  • no maps.Clear: served by builtin clear(m)
  • AbstractMap.Clone = maps.Clone
  • no maps.Contains; served by _, ok = m[k]; but see proposal #67377
  • no maps.Len: served by builtin len(m)
  • AbstractMaps.All = maps.All
  • no maps.Get: served by m[k]
  • no maps.Delete: served by delete(m, k)
  • AbstractMaps.DeleteFunc = maps.DeleteFunc
  • no maps.Lookup: served by v, ok = m[k]
  • AbstractMaps.Keys = maps.Keys
  • no maps.Set: served by prev, ok = m[k]; m[k] = newval
  • AbstractMaps.Values = maps.Values

Five of them (Clone, DeleteFunc, All, Keys, Values) are exactly parallel. All the rest are served by built-in operators.
We might want to propose adding maps.Contains. Contains is more useful than _, ok = s[k] in an expression context.

Activity

  1. added this to the Go1.28 milestone on Jul 28, 2026
  2. leaxoy commented on Jul 28, 2026

    @leaxoy

    Some personal thoughts—not necessarily sound, but offered for reference.

    1. rename _Abstract -> _I, _AbstractCollection -> _ICollection, short, readbility, and go have no inherit.
    2. Set add SupersetOf(S) bool and SubsetOf(S) bool
    3. Map.Set and Map.SetAll rename to Map.Insert and Map.InsertAll, same with Set.Insert
    4. ICollection add ContainsAny(iter.Seq[E]) bool method
    5. move Set.All to Collection.All, since any collection should also have iterate method
  3. willfaught commented on Jul 28, 2026

    @willfaught
    Contributor

    The collection library I'm most familiar with is Java's, so I guess I'm a bit biased in expecting certain aspects of it in any collection library. So let me probe the thinking behind this design a bit by asking:

    • Why is AbstractMap an AbstractCollection? Java's Map isn't a Collection because Collections are only for single objects:

      The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

      If AbstractCollection were defined in this way, an AbstractMap[K, V] could be something like AbstractCollection[Pair[K, V]] or AbstractCollection[struct{K; V}] or (if there were tuples in Go) AbstractCollection[(K, V)].

      Including AbstractCollection in AbstractMap as they are limits what AbstractCollection can do, hence why AbstractCollection can't have Set/Insert or Delete. This limitation would probably become more apparent as more sequence/non-map collection types are added. Including a list interface type in this design would force consideration of this aspect and allay concerns about generality.

      It's fine to define Go collections differently than Java's if there's a good reason to; I'd just like to understand that reason.

    Assuming AbstractMap is no longer an AbstractCollection or is an AbstractCollection with a pair-like element type:

    • Why not have AbstractCollection.Add/Remove? There's a nice symmetry and generality to those names.
    • Why not have AbstractCollection.All?

    The AbstractMap doc mentions ordered.Map, but I don't see ordered.Map listed in the associated issues. Is it part of this collections endeavor? If so, it would be good to include it in the issue list.

  4. jimmyfrasche commented on Jul 28, 2026

    @jimmyfrasche
    Member

    If set.Set is just a map[E]struct{} I see little use for a mapset package. I'd rather have a parallel set type that's just a map[E]bool (need not be in std, maybe shouldn't be).

    It would be more useful to have a type that adds all the methods to an ordinary map like

    package maps
    type Map[K comparable, V any] map[K]V
    func (m Map[K, V]) All() iter.Seq2[K, V] {
    	return All(m)
    }
    // etc.

    That way you could use it with those hypothetical future functions that abstract over collections.

  5. willfaught commented on Jul 28, 2026

    @willfaught
    Contributor

    What's the value in ContainsAll, DeleteAll, and SetAll? It seems like you can trivially do them yourself with a loop:

    myMap.DeleteAll(keys)
    for k := range keys {
        myMap.Delete(k)
    }

    Is the performance that much better if Map.DeleteAll does that for me? I can see how there would be some benefit if the elements are guaranteed to be ordered when accessing elements from ordered data structures, but that isn't necessarily the case: the elements can be in random order, forcing random jumps around ordered data structures.

  6. willfaught commented on Jul 28, 2026

    @willfaught
    Contributor

    I can see how DeleteFunc could be faster. Would a SetFunc/ReplaceFunc also be useful for mapping all elements?

  7. willfaught commented on Jul 28, 2026

    @willfaught
    Contributor

    I don't find the At name very intuitive, and it doesn't group together with Get by a common name prefix like the Contains*, Delete*, Set*, etc. methods. Perhaps Get(K) V and GetCheck(K) (V, bool) would group more intuitively. Also, given the two map operations v = m[k] and v, ok = m[k] being represented by these methods, I find it more intuitive for the simpler and more common operation to get the shorter method name.

  8. dominikh commented on Jul 28, 2026

    @dominikh
    Member

    What's the value in ContainsAll, DeleteAll, and SetAll? It seems like you can trivially do them yourself with a loop:

    That may be true for the built-in map type, but other map implementations may have much faster implementations of bulk operations. In particular, immutable data structures can relax some invariants during bulk operations (though then the interface doesn't really apply to immutable data structures...).

  9. willfaught commented on Jul 28, 2026

    @willfaught
    Contributor

    Not sure if this is the right place to comment on this, but I don't understand the reasoning behind the new container package names.

    Existing packages (heap, list, ring) are about specific data structures, not about data structure characteristics. Now there will be hash, ordered, and tree. I think I'd have trouble remembering what goes where. Why not have all set types under container/set, distinguished by names like Set and HashSet?

    It seems odd to have an entire package called tree. Sets can be trees, so should there be a tree-based Set in container/tree or container/set? Same for ordered: Sets can be ordered, so should there be an ordered Set in container/set or container/ordered?

    Perhaps there's a concern that a container/maps package would conflict with the maps package. I don't think that should necessarily result in splitting map implementations across multiple packages characterized by some other aspect. container/maps isn't great but would work fine, in my opinion.

    Even if there are no immediate designs for other data structures or any long-term plans for them, I think it's worthwhile to think about where other kinds of data structures would go under container/ to vet these new packages. Where would List, LinkedList, ArrayList, Stack, Queue, Trie, Graph, AVLTree, RedBlackTree, Pair, etc. go?

    Edit: Where would AbstractCollection, AbstractMap, and AbstractSet go?

  10. willfaught commented on Jul 28, 2026

    @willfaught
    Contributor

    This (including the container sub-packages) is a lot of API to vet, and the Go community collectively doesn't have a lot of experience designing collection data structures in Go (no offense intended; I include myself too). I worry that it's unlikely we will end up with a great, lasting design without warts on the first try. Problems may not be apparent until code is thoroughly exercised at scale.

    Perhaps it would be prudent to first ship these types in x/exp, gather feedback, make breaking changes as needed with new vN packages, and finally adopt them into the stdlib only when no more breaking changes would improve the design. Alias declarations from the final API in x/exp to the stdlib could make the migration to the stdlib easier, like what was done with the context package.

  11. willfaught commented on Jul 28, 2026

    @willfaught
    Contributor

    @dominikh What would be a mutable example?

  12. jimmyfrasche commented on Jul 28, 2026

    @jimmyfrasche
    Member

    If you embrace abstracting over collections and go for universal helpers first they can make it so everyone can X but you only need to specify X for your collection if it has some gain over the universal helper. For example:

    func ContainsAll[E any, C interface { Contains(E) bool }](collection C, seq iter.Seq[E]) bool {
    	if collection, native := C.(interface { ContainsAll(iter.Seq[E]) bool }); native {
    		return collection.ContainsAll(seq)
    	}
    	for e := range seq {
    		if !collection.Contains(e) {
    			return false
    		}
    	}
    	return true
    }
  13. jba commented on Jul 29, 2026

    @jba
    Contributor

    The interfaces presented in the top post are unexported and not part of any proposal. There is no need to comment on their names (edit). It is appropriate to discuss the method names and their signatures here.

  14. 100 remaining items

  15. leaxoy commented on Oct 16, 2026

    @leaxoy

    It could, but there are a number of places in the standard library itself that would want to make use of these collections; and, conversely, these collections may want to share implementations with std (e.g. hash.Map and the runtime's Swiss map). But the idea has merits.

    What you said makes sense; I really didn't think of that. 👍

  16. kamstrup commented on Oct 19, 2026

    @kamstrup

    I propose making the constraint interfaces read-only. This not only simplifies the interfaces, it also makes ownership more clear and harder to mess up.

    Ownership related bugs around maps and slices have been one of the gnarliest issues in almost Go projects I have worked on.

    Since constructors generally return concrete types, the code building the collection can access the mutating methods without issue. Functions that take collection interfaces then immediately show that they have no intent to mutate the argument.

    The collection package I implemented at work is designed around this, and it has held up quite well.

  17. adonovan commented on Oct 19, 2026

    @adonovan
    MemberAuthor

    I propose making the constraint interfaces read-only. This not only simplifies the interfaces, it also makes ownership more clear and harder to mess up.

    The constraint interfaces are for illustration only; they are not going to be exported, at least for now. If you are writing a generic function over one of these abstract collection types, you are free to pick any subset of the constraint type's methods, and by doing so to indicate exactly what requirements the generic function has on the type and what it can do with values of that type.

  18. aclements commented on Oct 29, 2026

    @aclements
    Member

    Based on the discussion above, this proposal seems like a likely accept.
    — aclements for the proposal review group

    This umbrella proposal is to add a set of collection packages to golang.org/x/exp, with the long-term intent of learning from experience using them and ultimately bringing them into the standard library. The individual collection types are given in sub-issues linked from #80590 (comment)

  19. moved this from Active to Likely Accept in Proposalson Oct 29, 2026
  20. willfaught commented on Nov 1, 2026

    @willfaught
    Contributor

    Having a container/list.ArrayList is useful.

    @willfaught Can you explain how? Concrete examples would help.

    @jba An array list can be grown by a callee without returning the updated collection to the caller. With a slice, a callee that appends must return the resulting slice for the caller to observe the new length and capacity and any new backing array. I find it surprising to ask whether this kind of type is useful at all when mutable, growable lists are standard in so many languages: C++, Objective-C, Java, C#, Python, Ruby, JavaScript, Rust, Swift, Haskell, Lisp—the list goes on. Doesn't that make the usefulness fairly self-evident? Go is unusual in not having one. I think the burden is on the case against providing it. It's fair to argue that array lists would overlap with slices or aren't sufficiently distinct to belong in the standard library—I have a counterargument to that, too—but the basic usefulness of a mutable, growable list seems well established.

    In general, I don't want to write:

    list = append(list, x)

    Rather, I want to write:

    list.Add(x)

    as I could with an array list in those languages I listed. With append, the caller has to use the returned slice to retain the updated length and any new backing array. That's extra state management when I just want a mutable, growable list.

    A number of you have focused on the interfaces: how they should be organized, which methods should go where, and so on. We're going to hold off on that discussion for now. The interfaces in this proposal are there only to express the commonalities among the various collections. They are not exported. They're not part of the proposal. In Go, unlike Java, you can write an interface for types that you don't control, so there's no particular need to provide them along with the collections. In the future, once we understand common use cases, we might consider adding suitable interfaces.

    @jba The abstract interfaces aren't directly useful to users yet; their current value is in helping coordinate method names and signatures across concrete types. If different types use different names or signatures for the same operation, they can't satisfy an interface that describes that operation. Users who want one interface to cover the affected types then have to create wrapper types that adapt the methods. We want to make sure that the method names and signatures chosen today will work well together. The interfaces are a useful way to check that we're making these choices consistently.

    For example, should stack-like collections use Push and Pop, and what should those methods return? Should set-like collections use Union, and with what signature? These choices affect whether users can define generic helpers that work across collection types. It seems useful to consider the interfaces those types could satisfy while settling the concrete APIs, even if those interfaces aren't exported now.

    One big package. collections.HashedMap, collections.SortedSet. Good discoverability and no need to pick a dimension to slice on. But the names are long and you have to compile the whole package to use any of it.

    @aclements Is package recompilation a significant concern? Go caches compiled package outputs locally, so subsequent builds can reuse them when the inputs match. Dead-code elimination reduces what goes into the final binary, but it doesn’t avoid compiling the package in the first place. Is the concern mainly first-build time, or linking performance?

    I'd be reluctant to split packages solely to reduce build work if that makes the API harder to navigate and understand. Is compilation cost significant enough here to justify that tradeoff?

    Expand the scope of the existing maps package to include these other map-like variants, and add a new top-level sets alongside it.

    This still allows types like maps.Hashed but without the conflict between maps and container/maps. But of course it also significantly expands the scope of maps.

    @apparentlymart I like this a lot. The existing maps and slices packages established top-level package names and conventions. It seems worth considering whether other collection packages—such as sets, graphs, and lists—could fit alongside them.

    Package name conflicts might seem trivial, but they introduce a very large jump in cognitive load because they turn something you don't think about at all (because goimports/gopls just handles it) into something you do need to consider.

    @neild I agree that package-name conflicts can add friction, but I’m not convinced that avoiding repeated package names is the right solution. Go’s hierarchical import paths allow related packages to use natural names, while local import aliases can disambiguate them. Could tooling or IDEs make ambiguous import choices more visible—for example, by showing which package it added or asking when multiple packages are plausible?

    We will omit the ContainsAll, DeleteAll and SetAll methods. They can each be easily written with a loop, and we don't see how making them methods on a data structure could improve their performance.

    @jba I thought more about my earlier question. DeleteAll can have a real performance benefit for a sorted map when the keys are supplied in sorted order: it can advance through the tree and keys together instead of doing a separate lookup for each key. That doesn't mean every map needs to implement bulk methods. It suggests they could be optional methods on concrete types whose representation can take advantage of them—for example, a sorted map could provide an optimized DeleteAll. Could the API leave room for such specialized methods without requiring them on every map?

    We are going to rename the At and Get methods to Get and Lookup:

    Get(K) V
    Lookup(K) (V, bool)

    There was much discussion about this, but ultimately we decided to follow the precedents in the standard library: https://pkg.go.dev/reflect#StructTag.Get and https://pkg.go.dev/os#Getenv.

    @jba I understand the precedent, but I still find Get and Lookup harder to remember as a pair than names that follow one pattern. The distinction is whether the operation reports whether a value was present, so I'd prefer names that make that distinction explicit and consistent—for example, Get/GetOK and Delete/DeleteOK. Lookup works for retrieval, but it doesn't suggest a naming pattern for operations like deleting or updating. Is there a reason to prefer operation-specific names over a consistent pattern?

    Some have noted that our APIs will not work for many implementations. For example, a map implementation that delays work to conduct more efficient batch operations will not be able to report whether a deletion removed a value that was present, so it can't implement a Delete method that returns a bool. In fact, it can't implement Len either. Both of those calls would require that it first discharge its pending work, since it may not know which pending deletions are for existing keys. That means that Delete and Len might occasionally run slowly.

    We understand that our APIs limit the possible implementations, but feel that the tradeoff is worth it. They are deliberately designed for in-memory, imperative, eager implementations. These tend to be easy to reason about and have predictable performance. No such implementation will find it challenging to report whether a deletion removed an existing key or to return its size in constant time. More esoteric designs have their uses, but those designs shouldn't be in the standard library unless they are widely useful.

    @jba Could there be two deletion methods: Delete(K), which returns nothing and can be deferred, and DeleteOK(K) (V, bool), which resolves pending work and reports the old value and whether the key existed? This adds API surface, and Len would still need to resolve pending work to return an exact count. But it would let an implementation defer operations when callers don't need the deletion result. I think that tradeoff is worth considering.

  21. changed the title [-]proposal: container/...: generic collection types[/-] [+]proposal: collection/...: generic collection types[/+] on Nov 4, 2026
  22. aclements commented on Nov 4, 2026

    @aclements
    Member

    No change in consensus, so accepted. 🎉
    This issue now tracks the work of implementing the proposal.
    — aclements for the proposal review group

    This umbrella proposal is to add a set of collection packages to golang.org/x/exp, with the long-term intent of learning from experience using them and ultimately bringing them into the standard library. The individual collection types are given in sub-issues linked from #80590 (comment)

  23. moved this from Likely Accept to Accepted in Proposalson Nov 4, 2026
  24. changed the title [-]proposal: collection/...: generic collection types[/-] [+]collection/...: generic collection types[/+] on Nov 4, 2026
  25. leaxoy commented on Nov 13, 2026

    @leaxoy

    I'm glad to see the substantial progress of this proposal.

    I have a personal thought: the current Set type is an alias for map, which allows bypassing the Set's API to manipulate the underlying data (I'm not sure if this was intentional or just a minor mistake). Is it possible to turn the Set into a struct with a map field inside?

    type Set[E comparable] map[E]struct{}
    
    -> 
    
    type Set[E comparable] struct {
        m map[E]struct{}
    }
  26. adonovan commented on Nov 13, 2026

    @adonovan
    MemberAuthor

    I have a personal thought: the current Set type is an alias for map, which allows bypassing the Set's API to manipulate the underlying data (I'm not sure if this was intentional or just a minor mistake). Is it possible to turn the Set into a struct with a map field inside?

    type Set[E comparable] map[E]struct{}

    ->

    type Set[E comparable] struct {
    m map[E]struct{}
    }

    It was intentional, so that all usual operations on maps (range, etc) work as usual.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    • Status
      Accepted

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions