WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Interfaces


The Go language provides another type of data, the interface, which defines all methods that have commonality, and any other type that implements these methods implements this interface.

example

/* Define the interface*/
type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}

/* Defining structure */
type struct_name struct {
   /* variables */
}

/* Implement interface method */
func (struct_name_variable struct_name) method_name1() [return_type] {
   /* Method implementation */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
   /* Method implementation*/
}

example

package main

import (
    "fmt"
)

type Phone interface {
    call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}

type IPhone struct {
}

func (iPhone IPhone) call() {
    fmt.Println("I am iPhone, I can call you!")
}

func main() {
    var phone Phone

    phone = new(NokiaPhone)
    phone.call()

    phone = new(IPhone)
    phone.call()

}

In the above example, we defined an interface Phone with a method call() inside the interface. Then we define a Phone type variable in the main function, and assign it to NokiaPhone and IPhone respectively. Then call the call () method, the output is as follows:

I am Nokia,< /span> I can call you!
I am iPhone, I can call you!< /pre>