On Sat, Jul 2, 2016 at 6:19 AM, Matt Harden <matt.har...@gmail.com> wrote:
> Conceptually, the value of a string is the sequence of bytes it contains,
> just like an array of bytes. It doesn't matter that the implementation of
> strings looks more like a slice internally. On the other hand the value of a
> slice is a reference to (part of) an underlying array, together with a
> length. In all cases == should compare values. I agree that it would be
> confusing to make == work for slices, because many people, myself included
> would intuitively want that to compare the contents of the slice (values
> from the underlying array) rather than the value of the slice itself which
> is essentially 3 pointers.

But what if you define slice comparison to be by value of the underlying array?

That would make []int{1} == []int{1} be true, despite the slices
pointing to different arrays.

It would probably also mean that

  a := make([]int, 0, 5)
  b := make([]int, 0, 7)

are equal since the two slices have equal elements, despite having
different capacities.

Defining slice comparison to be comparison on the values would mean
that you cannot tell if the slices refer to different underlying
arrays. Maybe you can use the reflect package to get hold of it
somehow and compare the pointers yourself.

Speaking of reflect, I just realized that what I'm proposing is to
define == as reflect.DeepEqual for slices. It seems to do everything
I'm talking about: slices from different arrays can compare equal, it
short-circuits in clever ways by looking at the length and noticing
when the slices refer to the same point in the same array.

> One nice feature of the current gc compiler AIUI is that it will avoid a
> copy in some circumstances when you convert a byte slice to a string and
> immediately use it as a map key. This helps with using []byte values to
> index into maps, but doesn't help when the []byte is part of a larger
> structure you want to use as a key.

Yes, I read about this optimization. In my opinion that is a great
optimization -- and the kind of optimization the compiler can do when
it knows the implementation of map and string. However, it shouldn't
be part of the language specification.

-- 
Martin Geisler

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to