Golang : interface - when and where to use examples
Question :
New comer to Golang will need to learn about interface eventually. So what exactly is interface? Where and when to use interface in Golang. Can show some examples?
Discussion :
What exactly is interface?
In Golang, an interface can be a type and also a set of methods. Interface ... according to the official documentation : "Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here. "
In simplest term, interface allows a developer to write program that deal with some uncertainty during run time and unknown data type during run time. Like allowing a function to accept whatever parameters
func AFunction(v interface{}) {
...
}
Where and when to use interface?
When you have a function that will behave according to the input data. The input data will determine which method to use.
For example :
package main
import (
"fmt"
)
type SayHelloIntFace interface {
SayHello()
}
type Person struct{}
// this method is tied to Person class
func (person Person) SayHello() {
fmt.Printf("Hello!")
}
type Dog struct{}
// this method is tied to Dog class
func (dog Dog) SayHello() {
fmt.Printf("woof! woof!")
}
func greeting(i SayHelloIntFace) {
i.SayHello()
}
func main() {
// instantiate objects
person := Person{}
dog := Dog{}
var i SayHelloIntFace
fmt.Println("\nPerson : ")
i = person
greeting(i)
fmt.Println("\n\nDog : ")
i = dog
greeting(i)
}
http://play.golang.org/p/DCmdWTvxYg
The greeting() function will accept the input data type SayHelloIntFace(object) and because ... "Interfaces in Go provide a way to specify the behavior of an object"....this is why the program aforementioned will be able to automatically select which SayHello()
method to use.
Another place where your program want to use interface is when your program can't determine the input data type during run time. For example, your program is expecting JSON data and you want to un-marshal the JSON data to map. You know that top-level keys are strings, but not the lower-level values data type during runtime. It could be strings, integer or rune. Interface type is perfectly suited for this kind of situation.
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Given a possibly complex JSON object
msg := "{\"assets\" : {\"old\" : 123}}"
// We only know our top-level keys are strings - "assets"
// but the lower-level value could integer, rune or string
// therefore, we create a make use of interface{} type
mp := make(map[string]interface{})
// Decode JSON into our map
err := json.Unmarshal([]byte(msg), &mp)
if err != nil {
println(err)
return
}
// See what the map has now
fmt.Printf("mp is now: %+v\n", mp)
// Iterate the map and print out the elements one by one
// Note: that mp has to be deferenced here or range will fail
for key, value := range mp {
fmt.Println("key:", key, "value:", value)
}
}
http://play.golang.org/p/2nR_wh6BiV
Hope you find this short tutorial useful in understanding Golang interface.
References :
https://golang.org/doc/effectivego.html#interfacesand_types
https://www.socketloop.com/tutorials/golang-implementing-class-object-oriented-programming-style
See also : Golang : Implementing class(object-oriented programming style)
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.2k Golang : GUI with Qt and OpenCV to capture image from camera
+15.2k Golang : rune literal not terminated error
+5.5k Fix yum-complete-transaction error
+6.8k Golang : Find the shortest line of text example
+11.1k Golang : How to flush a channel before the end of program?
+10.9k Golang : Roll the dice example
+12.6k Python : Convert IPv6 address to decimal and back to IPv6
+7.8k How to show different content from website server when AdBlock is detected?
+30.5k Golang : Interpolating or substituting variables in string examples
+16.7k Golang : Get input from keyboard
+7.3k Android Studio : AlertDialog to get user attention example
+6.9k CloudFlare : Another way to get visitor's real IP address