liveBook · Manning

Empty interface

As explained in Learn Go with Pocket-Sized Projects

any is Go's predeclared constraint that permits any type as a generic type argument and is equivalent to interface{}.

any is Go’s least-constraining generic type constraint: it permits every type. Use it when a function, structure, or variable should remain reusable across concrete types. section 7.1.1 section 7.6

A reusable generic function

func prettyPrint[T any](t T) { fmt.Printf("> %v", t) } accepts values such as float64 and string. Calling prettyPrint[float64](.25) supplies the type explicitly; calling prettyPrint("pockets") lets the compiler infer T. section 7.1.1

func prettyPrint[T any](t T){
    fmt.Printf("> %v", t) #1
}

prettyPrint[float64](.25) #2
prettyPrint[string]("pockets")

Compare explicit type arguments for float64 and string in one compact generic-function example. section 7.1.1

The compiler generates the required concrete flavors at compilation time, while the generic implementation removes duplicated functions. Replace any with narrower constraints when the implementation needs operations such as comparison or ordering. section 7.1.1 section 7.6

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines any as an unconstrained type requirement and demonstrates explicit arguments, inference, and compilation of concrete instantiations.
Examples
Uses prettyPrint with float64 and string values, showing both explicit type arguments and compiler-inferred type arguments.
What you can do after
Build it from scratch: write generic Go functions that accept multiple concrete types and invoke them with explicit or inferred types.
How it connects
Connects any with generics, type constraints, type inference, comparable, and ordered constraints.

Also explained in

Compare how 4 books explain empty interface →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.