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 (bChessSport)TypeSport() { fmt.Printf("%s goes sport\n", b.Name) } func (bFootballSport)TypeSport() { fmt.Printf("%s goes Football Sport\n", b.Name) } func main() { var athletes1 ChessSportathletes1.Name = "Joko"athletes1.() varTypeSportathletes2FootballSportathletes2.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 []Sportathletes= append(,athletes)athletes1athletes= append(,athletes)athletes2
Hopefully, this article useful. Thank you
Other Topics:
How to build NGINX RTMP module, Setup Live Streaming with NGINX RTMP module, Publishing Stream with Open Broadcaster Software (OBS), Create Adaptive Streaming with NGINX RTMP, Implementing Filtergraph in Streaming with NGINX RTMP, How to Implement Running Text in Streaming with NGINX RTMP, How to build OpenSceneGraph with Code::Blocks, How to build OpenSceneGraph with Visual Studio 2010, Building Geometry Model, How to run OpenSceneGraph with Netbean IDE 8.2 C++, Rendering Basic Shapes, Using OSG Node to Load 3D Object Model, Rendering 3D Simulator with OpenSceneGraph, How to compile wxWidgets with Visual Studio 2010, How to Setup Debugging in Golang with Visual Code
No comments:
Post a Comment