Operator constraints

September 19, 2023

Last week I inconspicuously skipped over one sentence in the spec, the last sentence in the section on Operands, and jumped straight ahead to the section on Qualified identifiers.

This is because the sentence didn’t make immediate sense to me, and I needed time to research it. I’ve done that research now, so, let’s jump back and cover the missed territory.

Operands

Implementation restriction: A compiler need not report an error if an operand’s type is a type parameter with an empty type set. Functions with such type parameters cannot be instantiated; any attempt will lead to an error at the instantiation site.

That’s pretty dense, I think. And it took me a while to understand what it was even talking about, let alone why this “restriction” is included. So let me try to help you do the same.

First, what is an empty type set?

Well, it’s a type set that matches 0 types. Makes sense. What’s an example? Here’s an example:

interface {
  int
  Foo()
}

No type can be both an int, and have a method called Foo(), for the simple reason that int is a predefined type, and has no methods at all.

So you could define a type parameter that contains such an empty type set, as in this function definition:

func x[A interface {
	int
	Foo()
}]() {
}

But since no types match the empty type set, this function can never be instantiated. It’s meaningless code that will never be executed.

Okay, so that’s what the restriction is about… operands that match this pattern.

But why does this restriction exist?

Well, the TL;DR; is: It’s not as easy as one might initially think, to detect empty type sets. So to prevent the possibility of compilation times potentially being very long (possibly infinitiely long), the spec does not require the compiler to do this determination, instead deferring to runtime, where the check is easy to perform.

If you’re interested in all the nitty gritty on this topic, check out this amaing blog post by Axel Wagner: Operator constraints in Go.

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 .