DEV Community

Jonathan Hall
Jonathan Hall

Posted on • Originally published at boldlygo.tech

3

Resolving type parameter ambiguities

#go

I stumbled upon a bit of a WTF in the Go Specification, while writing my daily Go email and had to dig in a bit to make sense of it:

Type parameter declarations

A parsing ambiguity arises when the type parameter list for a generic type declares a single type parameter P with a constraint C such that the text P C forms a valid expression:

type T[P *C] …
type T[P (C)] …
type T[P *C|Q] …
…

Image description

If you’re up for it, I’ll try to break this thing down. If you’re not up for it, no worries. See you later! 👋😆

Let’s consider the first example provided: type T[P *C] …. How can this be ambiguous?

Well, it looks like an array type declaration, where the array length is derrived from a constant expression, such as in this example:

const P = 3
const C = 4

type T [P * C]int // T is of type [12]int
Enter fullscreen mode Exit fullscreen mode

Other expressions are possible, too, which is what leads to this possible ambiguity.

So, we need a way to solve this WTF scenario, and Go gives us two of them…

In these rare cases, the type parameter list is indistinguishable from an expression and the type declaration is parsed as an array type declaration. To resolve the ambiguity, embed the constraint in an interface or use a trailing comma:

type T[P interface{*C}] …
type T[P *C,] …

So either wrap your constraint in interface{…}, or add a magical comma at the end. Poof! problem solved.

But still. WTF?!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs