Unions of type sets

May 1, 2023

General interfaces

Union elements denote unions of type sets:

// The Float interface represents all floating-point types
// (including any named types whose underlying types are
// either float32 or float64).
type Float interface {
	~float32 | ~float64

Here we see our first example of a union of type sets. The example shows an interface of all types with an underlying float type. The equivalent for integer types is a bit longer, due to the large number of distinct integer types in Go, but would look like:

type Int interface {
	~uint8 | ~uint16 | ~uint32 | ~uint64 | ~int8 | ~int16 | ~int32 | ~int64

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

Share this

Related Content

Implementing an interface

It feels like it’s been a month since we started on interfaces. Today we’re covering the final section on this topic! Implementing an interface A type T implements an interface I if T is not an interface and is an element of the type set of I; or T is an interface and the type set of T is a subset of the type set of I. A value of type T implements an interface if T implements the interface.

Type parameter restrictions

We’ll get to a full discussion of type parameters later on, but knowing at least what they look like is useful for the next section. So here’s an example, used in the definition of a generic function: func min[T ~int|~float64](x, y T) T { In this example, min[T ~int|~float64] represents the type parameter. With that in mind… General interfaces … The type T in a term of the form T or ~T cannot be a type parameter, and the type sets of all non-interface terms must be pairwise disjoint (the pairwise intersection of the type sets must be empty).

Interface type sets

With what we’ve learned so far about interfaces, we can now draw some general conclusions about the precise definitions of an interfce’s type set. The spec summarizes nicely. General interfaces … Together with method specifications, these elements enable the precise definition of an interface’s type set as follows: The type set of the empty interface is the set of all non-interface types. The type set of a non-empty interface is the intersection of the type sets of its interface elements.