Go Interfaces
Working with interfaces for polymorphism
Interface Definition
type Shape interface { # define interface
Area() float64 # method signature
Perimeter() float64
}
Implementing Interface
type Rectangle struct { # define struct
width, height float64
}
func (r Rectangle) Area() float64 { # implement method
return r.width * r.height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.width + r.height)
}
Using Interfaces
var s Shape # declare interface variable
s = Rectangle{width: 10, height: 5} # assign concrete type
area := s.Area() # call interface method
Empty Interface
var i interface{} # can hold any type
i = 42 # assign int
i = "hello" # assign string
value := i.(string) # type assertion
value, ok := i.(int) # safe type assertion
Type Switch
switch v := i.(type) { # check type
case int:
fmt.Println("Integer:", v)
case string:
fmt.Println("String:", v)
default:
fmt.Println("Unknown type")
}