Interfaces · 3 MIN READ

any is interface{}, and it has no methods

Report the dynamic type of a value held in any.

The Tour's "The empty interface" page: interface{} specifies zero methods, so every type implements it. any is the alias. fmt.Print takes ...any for that reason.

Holding a value in any throws the static type away. Getting it back is a type assertion or a type switch — the two-value form, or you panic. %T in fmt is the cheap way to see what is inside, and it is what this lesson asks you to return.

SEE THE IDEA

any preserves a dynamic value but promises no methods

  1. 01

    Store

    go
    var value any = "go"

    Any type can be held

  2. 02

    Recover type

    go
    text, ok := value.(string)

    Ask for a specific dynamic type

  3. 03

    Use safely

    go
    if ok { use(text) }

    Operate after checking the assertion

any is an alias for interface{}; it is not a compile-time generic type parameter.

In practice

Use any at a deliberately untyped boundary, such as decoding heterogeneous data. Prefer a concrete type when the caller and callee already agree on the shape. A checked type assertion reports failure without panic; an unchecked assertion is appropriate only when the contract guarantees the type.

Watch out

Saying any accepts every type does not mean every operation is legal on the resulting interface value.

Official reference ↗

Work through the exercise

go
package main

// Kind returns the dynamic type, as fmt would: "int", "string",
// "*int". A nil any prints as <nil>.
func Kind(value any) string {
	return ""
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.