Use any and interface values
Use any and interface values
any is an alias for interface{} introduced in Go 1.18. It requires no methods, so every ordinary Go value can be assigned to it. The variable still has a static type: any. Operations requiring a concrete type are not available directly on it.
package main
import ( "fmt")
func main() { var x any = 42 fmt.Printf("%T %v\n", x, x) x = "Go" fmt.Printf("%T %v\n", x, x)}Assigning another value changes the dynamic type and value, not the declared type of x. The formatting verbs %T and %v display the concrete type and value. You cannot write x+1 merely because x once held an integer.
Expected output:
int 42string GoCollect heterogeneous values
package main
import ( "fmt")
func main() { items := []any{3, "tea", true} for _, v := range items { fmt.Printf("%T:%v\n", v, v) }}A slice of any can hold different concrete types. Use []int when all values are integers; it preserves stronger compile-time checks. []int is not directly assignable to []any because slice element types differ. Convert elements individually when necessary.
Expected output:
int:3string:teabool:trueTry it locally
Create []any containing 7, "Go", and false. Print each type and value on its own line using %T and %v.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Interfaces 04: Use any and interface values
Check the lesson objective before moving on.
What is any an alias for?
Can an any variable be used directly with integer addition?