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
+8.1k Golang : Number guessing game with user input verification example
+4.9k Golang : Display packages names during compilation
+5.8k Golang : Extract unicode string from another unicode string example
+14.3k Golang : Convert(cast) int to float example
+30.5k Golang : Download file example
+16.8k Golang : How to save log messages to file?
+15.2k Golang : ROT47 (Caesar cipher by 47 characters) example
+11.1k Golang : Delay or limit HTTP requests example
+44.5k Golang : Use wildcard patterns with filepath.Glob() example
+27.1k Golang : Convert CSV data to JSON format and save to file
+16.9k Golang : Find file size(disk usage) with filepath.Walk
+16.2k Golang : Check if a string contains multiple sub-strings in []string?