Middle
Why can an empty interface in Go be assigned to any type?
sobes.tech AI
Answer from AI
The empty interface interface{} contains no methods. Any type in Go can satisfy an interface that requires no methods. Therefore, the value of any type can be assigned to a variable of type interface{} or passed to a function accepting interface{}. Essentially, interface{} acts as a container for a value of any type, storing both the value itself and its type.
package main
import "fmt"
func main() {
var i interface{} // Declare a variable of empty interface type
i = 42 // Assign an int
fmt.Printf("Value: %v, Type: %T\n", i, i)
i = "hello" // Assign a string
fmt.Printf("Value: %v, Type: %T\n", i, i)
i = true // Assign a bool
fmt.Printf("Value: %v, Type: %T\n", i, i)
i = struct{}{} // Assign an empty struct
fmt.Printf("Value: %v, Type: %T\n", i, i)
}
Casting to a specific type from interface{} is possible using type assertion or a type switch.
package main
import "fmt"
func main() {
var i interface{} = "world"
// Type assertion
s, ok := i.(string) // Check if the value is a string
if ok {
fmt.Println("Type assertion successful:", s)
} else {
fmt.Println("Type assertion failed")
}
// Type switch
switch v := i.(type) {
case int:
fmt.Println("Type is int, value:", v)
case string:
fmt.Println("Type is string, value:", v)
default:
fmt.Println("Unknown type")
}
}