liveBook · Manning

Underlying type

As explained in 100 Go Mistakes and How to Avoid Them

An underlying type is the type that determines the representation and core identity shared by a defined Go type and its underlying type.

A common mistake is using int when a generic constraint should accept defined integer types. int admits only the int type; ~int admits every type whose underlying type is int. section 2.9.1

Why ~int matters

Define type customInt int and give it a String() string method. A constraint containing ~int and String() string accepts customInt because its underlying type is int; replacing ~int with int causes a compilation error. section 2.9.1

type customConstraint interface {
    ~int
    String() string
}

This constraint combines an underlying-type approximation with a required method, making the distinction between int and ~int concrete. section 2.9.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains the difference between int and ~int through a custom type and a compilation failure.
Examples
Uses customInt, a String method, and constraints containing ~int or int.
What it assumes
Assumes familiarity with Go types, interfaces, methods, and generic type constraints.
What you can do after
Evaluate generic constraints and choose ~T when defined types sharing T's underlying type should be accepted.
How it connects
Connects underlying types to type constraints, defined types, methods, and generics.

Also explained in

Compare how 2 books explain underlying type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.