Empty interface
The empty interface interface{} has no methods, so every type satisfies it. It is the type of a value whose concrete type is decided at runtime. any is an alias for the same type.
Detailed Explanation
Before Go 1.18, interface{} was how you wrote "some value." fmt.Println still takes ...any. JSON unmarshalling into an unknown shape still uses map[string]any. The empty interface is a box: it holds a type and a value, and you get the value back with a type assertion or a type switch.
Every type is in the set. int, string, *os.File, []byte, and your Session all assign to interface{}. That is not the same as a union. The compiler will not remind you to handle int vs string. You handle it, or you pass the value to something else that does (fmt, reflect, json).
It is still an interface. var x interface{} is nil. x = 0 is not nil. x = (*int)(nil) is not a nil interface. Calling a method on x does not compile — there are no methods — unless you assert to a type that has them.
Prefer a real interface or a type parameter. A function func Process(v interface{}) that immediately switches on int and string is a generic function that forgot its type parameter, or two functions. func Process[T any](v T) still accepts every type but keeps T in the caller. Use interface{} / any when the set of types is not known at compile time (decoding JSON, printing, a heterogeneous slice).
[]interface{} is not a []T. You cannot assign []string to []interface{}. You must allocate a new slice and copy. This is a common compile error for people who expect covariance.
What it costs. Each assignment boxes the value: a small integer in an interface is a heap allocation in many cases (escape analysis may stack-allocate). A tight loop that stores int in []any is slower than []int. The larger cost is lost type information: bugs move from compile time to assertions.
Code Examples
package main
import "fmt"
func printAny(v interface{}) {
fmt.Printf("%T %v\n", v, v)
}
func main() {
printAny(3)
printAny("shop")
printAny(struct{ N int }{N: 1})
}func asInt(v interface{}) (int, bool) {
n, ok := v.(int)
return n, ok
}func copyAny(ss []string) []interface{} {
out := make([]interface{}, len(ss))
for i, s := range ss {
out[i] = s
}
return out
}Common Gotchas
`[]T` is not `[]interface{}`
the conversion is a loop or a typed `any` slice built element by element.
Type assertions panic without the comma-ok form
`v.(int)` on a string panics. Use `n, ok := v.(int)`.
A typed nil inside `interface{}` is not nil
check with a type switch if you must distinguish.
New code should write `any`
it is the same type as `interface{}`. Keep `interface{}` when you are matching older docs or generated code.