Middle
How is an empty interface in Go related to a regular interface?
sobes.tech AI
Answer from AI
The empty interface interface{} is an interface that has no methods. A regular interface has one or more methods.
The key points are:
- A type that implements any set of methods (or none) automatically satisfies the empty interface. Any value of any type can be assigned to a variable of type
interface{}. - A type that implements the methods of a regular interface satisfies that interface.
- Therefore, a type that implements a regular interface also automatically satisfies the empty interface, since it is any type.
Example:
package main
import "fmt"
// Regular interface
type Speaker interface {
Speak() string
}
// Struct implementing Speaker
type Person struct {
Name string
}
func (p Person) Speak() string {
return "Hello, my name is " + p.Name
}
func main() {
// Variable of type Speaker
var s Speaker = Person{Name: "Alice"}
fmt.Println(s.Speak())
// Variable of type empty interface.
// s can be assigned to i, since it is any type.
var i interface{} = s
fmt.Println(i) // Outputs the value of s
// Empty interface variable can hold any value,
// even those that do not implement Speaker.
i = 42
fmt.Println(i)
i = "hello"
fmt.Println(i)
}
The empty interface is used for working with data of unknown or heterogeneous types, allowing storage of values of any type but losing information about the specific type and its methods (type assertion or type switch is required to access underlying values and methods). A regular interface is used to define a behavior contract, focusing on a set of methods that must be implemented.