Open In App

Interfaces in Golang

Go language interfaces are different from other languages. In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires. Or in other words, the interface is a collection of methods as well as it is a custom type.

How to create an interface?

In Go language, you can create an interface using the following syntax:



type interface_name interface{

// Method signatures

}

For Example:

// Creating an interface
type myinterface interface{

// Methods
fun1() int
fun2() float64
}

Here the interface name is enclosed between the type and interface keywords and the method signatures enclosed in between the curly braces.



How to implement interfaces?

In the Go language, it is necessary to implement all the methods declared in the interface for implementing an interface. The go language interfaces are implemented implicitly. And it does not contain any specific keyword to implement an interface just like other languages. As shown in the below example:

Example:




// Golang program illustrates how
// to implement an interface
package main
  
import "fmt"
  
// Creating an interface
type tank interface {
  
    // Methods
    Tarea() float64
    Volume() float64
}
  
type myvalue struct {
    radius float64
    height float64
}
  
// Implementing methods of
// the tank interface
func (m myvalue) Tarea() float64 {
  
    return 2*m.radius*m.height +
        2*3.14*m.radius*m.radius
}
  
func (m myvalue) Volume() float64 {
  
    return 3.14 * m.radius * m.radius * m.height
}
  
// Main Method
func main() {
  
    // Accessing elements of
    // the tank interface
    var t tank
    t = myvalue{10, 14}
    fmt.Println("Area of tank :", t.Tarea())
    fmt.Println("Volume of tank:", t.Volume())
}

Output:

Area of tank : 908
Volume of tank: 4396

Important Points


Article Tags :