Restrictions on underlying type terms

April 27, 2023

General interfaces

In a term of the form ~T, the underlying type of T must be itself, and T cannot be an interface.

type MyInt int

interface {
	~[]byte  // the underlying type of []byte is itself
	~MyInt   // illegal: the underlying type of MyInt is not MyInt
	~error   // illegal: error is an interface
}

Once again, the spec examples are pretty well explained. TL;DR; the ~ prefix must always be associated with an underlying data type.

Not explicitly mentioned here, though still important, you can use a struct as the underlying type, but not a named struct. That is, you must use an anonymous struct, which can get quite verbose:

type Person {
	Name string
	Age  int
}

interface {
	Person // Valid

	~Person // illegal: underlying type of MyStruct is struct{Name string; Age int}

	~struct{Name string; Age int} // Valid
}

Quotes from The Go Programming Language Specification Version of December 15, 2022


Share this

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

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe