Skip to content

proposal: unique: Make for slices #73598

Open

Description

@seankhliao

Proposal Details

// Slice returns a globally unique handle for the slice. Slices are equal as compared by [slices.Equal].
// Handle stores a cloned copy of the slice. Every slice returned by [Handle.Value] for a given [Handle]
// shares the same backing array: slices must be cloned before modification.
func Slice[S ~[]E, E comparable](s S) Handle[S]

I'd like to be able to intern slices, the building block for collections of values in Go.
While slices aren't natively comparable in Go, they do have a fairly straightforward equality comparison as demonstrated with slices.Equal.

As unique currently already clones its inputs, I expect slices to be treated similarly: the slice and its backing array are cloned to a new copy, detached form the input.

A potential footgun is the value returned by Value: the elements of the backing array of the returned slice may be modified by the user, resulting in a different slice from the value passed in / represented by the key.
This can be mitigated by cloning the slice again in Value, but I don't think it should be done automatically by Value.

The cost of calculating the unique Handle means using unique may only make sense for sufficiently large values, or values with string-like properties where values hold pointers to readonly data. While we can't express that in Go's type system today, with sufficient care it can be used to optimize user code.

cc @mknyszek

Activity

  1. added this to the Proposal milestone on May 5, 2025
  2. gabyhelp commented on May 5, 2025

    @gabyhelp

    Related Issues

    (Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

  3. mateusz834 commented on May 5, 2025

    @mateusz834
    Member

    This would require a change in Handle signature.

    type Handle[T comparable] struct {}

    into

    type Handle[T any] struct {}

    Can we change that in terms of backwards-compatibility?

  4. added
    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a tool
    on May 5, 2025
  5. mknyszek commented on May 5, 2025

    @mknyszek
    Contributor

    The concept of a frozen or 'stable' value would help a lot in writing APIs like this.

    At face value, we've got two less-than-ideal options:

    1. Mutating the slice returned by Handle accidentally breaks how unique fundamentally works.
    2. Cloning the slice which would require a heap allocation in today's compiler.

    The problems with (2) might be possible to avert in many cases with a smarter compiler. Currently the compiler can't stack-allocate dynamically sized things, but if we had an answer to that, it might work better. (Value would need to be inlined, but that doesn't seem that hard to ensure.)

    A third alternative might be to have a new API to pass a slice to copy into. This would benefit from a dedicated 'slice handle' type. For example:

    package unique
    
    // ...
    func MakeSlice[S ~[]E, E comparable](s S) Slice[E]
    
    // Slice is like Handle but for slices. The slice value represented by SliceHandle is immutable.
    type Slice[E comparable] struct { ... }
    
    // Len returns the length of the slice represented by the handle.
    func (s Slice[E]) Len() int
    
    // Copy copies the slice represented by the slice handle into dst.
    //
    // This works like the copy builtin. If dst is not large enough to hold the data, a partial copy is
    // made, returning the number of elements copied. Use Len to size dst and copy all the necessary
    // data out.
    func (s Slice[E]) Copy(dst []E) int
    

    EDIT: Updated based on @mateusz834's comment below.

    We could also provide a separate Value or Clone method for convenience.

    This API is unfortunate but also doesn't seem that bad.

  6. mknyszek commented on May 5, 2025

    @mknyszek
    Contributor

    Oof, though, I can see my suggestion above quickly devolving into "let's support all immutable operations on slices." 😅

    You could also imagine:

    func (s Slice[E]) Index(int) E
    func (s Slice[E]) All() iter.Seq[E]
    

    ... On the other hand, maybe that's not that bad? It is a lot of API just to work around the inability to express an immutable slice.

    EDIT: Updated based on @mateusz834's comment below.

  7. mateusz834 commented on May 5, 2025

    @mateusz834
    Member

    One drawback of this API is the signature, say you want to use it in a struct and then you have to specify these two type-params. I think in the std we only used the [S ~[]E, E comparable] form in funcs, where they are nicely infered.

    type Slice[S ~[]E, E comparable] struct {}
    type _ struct {
        field unique.Slice[[]int, int]
    }
  8. DeedleFake commented on May 5, 2025

    @DeedleFake

    Would it be feasible to create an Immutable[T any] or View[T any] in slices that, if T is comparable, could itself be used with unique instead? Immutable slice views could be useful for a variety of things.

  9. mknyszek commented on May 5, 2025

    @mknyszek
    Contributor

    @mateusz834 Makes sense. It should probably just be type Slice[E comparable] struct { ... }. Updated my comments above.

    @DeedleFake That might be one way to go about it, yeah. unique could just return the slices.Immutable[T] (or whatever it would be called) instead.

    The path this is going down is starting to seem more like a language change and that's a much deeper rabbit hole...

  10. mateusz834 commented on May 5, 2025

    @mateusz834
    Member

    Also there is a third option to just document that the slice cannot be modified and put the slice in a read-only memory? (so that modifying it faults).

  11. mknyszek commented on May 5, 2025

    @mknyszek
    Contributor

    Also there is a third option to just document that the slice cannot be modified and put the slice in a read-only memory? (so that modifying it faults).

    That's unfortunately significantly harder than it sounds, especially for small slices.

  12. mknyszek commented on May 5, 2025

    @mknyszek
    Contributor

    The path this is going down is starting to seem more like a language change and that's a much deeper rabbit hole...

    Aaaand we've been down this rabbit hole before. I'm not surprised. See https://docs.google.com/document/d/1-NzIYu0qnnsshMBpMPmuO21qd8unlimHgKjRD9qwp2A/edit?tab=t.0 which I found from #20443 (comment). Some of this is less relevant in our modern type-parametrized world, and the original proposal was also suggesting that []T -> immutable []T would not force a clone operation. I would argue that it should.

  13. apparentlymart commented on May 5, 2025

    @apparentlymart

    Due to the general lack of "reference to const data" types in Go today, it's already relatively common to return mutable-in-practice slices with a documented convention or requirement that the caller mustn't modify them, and also relatively common to make just-in-case copies to ensure encapsulation. The ecosystem seems pretty divided on which to use in which situations, but the fact that both already exist seems to suggest that both are defensible, even if not ideal for all applications.

    If we do decide that Value should return a slice over the same backing array to all callers with just a documentation warning not to modify it then I think Value should ensure that there's no excess capacity in what it returns, so that uses of append on the result will always definitely allocate a new slice. (I expect that's a natural consequence of copying to a new backing array, but I'm suggesting to document it as a guarantee.)

    (I think I actually prefer the later-discussed formulation where unique.Slice is a type, similar to how sync.Map is a type rather than just a set of conventions for working with a plain map, but the above comment is intended for the original proposal.)

  14. EdSchouten commented on Nov 28, 2025

    @EdSchouten

    Another option would be to have some kind of FrozenSlice[T] type that is comparable. Just like how string could be thought of as a frozen []byte. Then you could just call unique.Make(FrozenSlice[T](...)).

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposalcompiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions