Wednesday, February 13, 2019

Go Interfaces Tutorial

Typically, if you see a function or a method that expects an empty interface, then you can typically pass anything into this function/method.

Let's see first example main.go below:
package main

import (
 "fmt"
)

func myFunc(x interface{}) {
 fmt.Println(x)
}

func main() {
 var my_number int
 my_number = 50
 
 myFunc(my_number)
}

If we then go to run this then we should see that it runs successfully and prints out our integer value:

$ go run main.go
50


Interface is very useful, by defining a function that takes in an interface{}, we essentially give ourselves the flexibility to pass in anything we want. 
If we define a type based off this interface then we are forced to implement all of the functions or methods defined within that interface type.

Let's see second example main.go below:
package main

import "fmt"

type Sport interface {
 TypeSport()
}

type ChessSport struct {
 Name string
}

type FootballSport struct {
 Name string
}

func (b ChessSport ) TypeSport() {
 fmt.Printf("%s goes sport\n", b.Name)
}

func (b FootballSport ) TypeSport() {
 fmt.Printf("%s goes Football Sport\n", b.Name)
}

func main() {
 var athletes1 ChessSport
 athletes1.Name = "Joko"
 athletes1.TypeSport()

 var athletes2  FootballSport 
 athletes2.Name = "Budi"
 athletes2.TypeSport()
}

Should we wish, we could then create an array of type Sport which could store both our ChessSport and FootballSport objects.

var athletes []Sport
athletes = append(athletes , athletes1)
athletes = append(athletes , athletes2)

Hopefully, this article useful. Thank you 


Other Topics:

No comments:

Post a Comment