Comparison operators, part III

February 14, 2024

Today we continue through the list of data types and how comparison and ordering works on each.

Comparison operators

  • Channel types are comparable. Two channel values are equal if they were created by the same call to make or if both have value nil.

Notice that channel comparison is effectively a comparison of identity. Not type or content.

Two channels may have the same type and contents, but be unequal:

ch1 := make(chan int)
ch2 := make(chan int)
fmt.Println(ch1 == ch2) // false
  • Interface types that are not type parameters are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.

This makes intuitive sense, I think. Well, at least mostly.

This makes sense:

var a any = int(3)
var b any = int(3)
fmt.Println(a == b) // true

Arguably this makes slightly less sense:

var x error
var y any
fmt.Println(x == y) // true

But it shouldn’t matter. I’ve never wanted to do such a comparison, and can’t really imagine a time when I would want to. But fear not. If you really want to do this, it can be accomplished with some reflection shennanigans:

xt := reflect.TypeOf(&x).Elem()
yt := reflect.TypeOf(&y).Elem()
fmt.Println(xt == yt) // prints false
  • A value x of non-interface type X and a value t of interface type T can be compared if type X is comparable and X implements T. They are equal if t’s dynamic type is identical to X and t’s dynamic value is equal to x.

Here we have a couple of those typically dense sentences we need to pull apart to make sense of.

var x int = 3      // non-interface type, and the type is comparable, because ints are comparable
var y any = int(3) // Interface type, dynamic type is `int`, same as x's type, and the dynamic values are equal

fmt.Println(x == y) // true

We have three more types to go through, which I’ll save for tomorrow.

Quotes from The Go Programming Language Specification Version of August 2, 2023


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe