Go Interfaces
Go Language - Interfaces
Another data type provided by Go programming called interfaces which is a set of method signatures. To implement an interface in Go, we just need to implement all the methods in the interface. If a variable has an interface type, then we can call methods that are in the named interface.
The interface type that specifies zero methods is known as the empty interface interface{}. A variable of empty interface type can hold values of any type since every type implements at least zero methods. An interface value is represented as a pair of a concrete value and a dynamic type: [Value, Type]. The zero value of an interface type is nil, which is represented as [nil, nil]. Calling a method on a nil interface is a run-time error. However, it’s quite common to write methods that can handle a receiver value [nil, T], where T != nil.
Syntax
/* define an interface */
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen[return_type]
}
/* define a struct */
type struct_name struct {
/* variables */
}
/* implement interface methods*/
func (struct_name_variable struct_name) method_name1() [return_type] {
/* method implementation */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
/* method implementation */
}
Program Example :
CODE/PROGRAM/EXAMPLE
package main
import("fmt""math")
/* define an interface */
type Shapeinterface{
area()float64}
/* define a circle */
type Circlestruct{
x,y,radius float64
}
/* define a rectangle */
type Rectangle struct{
width,height float64
}
/* define a method for circle (implementation of Shape.area())*/
func(circle Circle)area()float64 {
return math.Pi*circle.radius *circle.radius
}
/* define a method for rectangle (implementation of Shape.area())*/
func(rect Rectangle)area()float64 {
return rect.width *rect.height
}
/* define a method for shape */
func getArea(shape Shape)float64 {
return shape.area()
}
func main(){
circle :=Circle{x:0,y:0,radius:5
}
rectangle :=Rectangle{width:7,height:5}
fmt.Printf("Circle area: %f\n",getArea(circle))
fmt.Printf("Rectangle area: %f\n",getArea(rectangle))
}
Output :
Circle area: 78.539816
Rectangle area: 35.00000