I would like to understand the interface type with a simple example of it's use in Go (Language).
I read the web documentation, but I don't get it.
The primary task of an interface is to provide only function signatures consisting of the name, input arguments and return types. It is up to a type (e.g. struct type) to implement functions. Interfaces are also reffered to as exposed APIs or contracts.
Just like defining a struct, Go uses curly braces ( {} ) to surround the definition of the interface. In comparison to defining structs, we only define the interface's behavior; that is, “what can this type do”. In the case of the Stringer interface, the only behavior is the String() method.
To implement an interface in Go, we just need to implement all the methods in the interface. Here we implement geometry on rect s. The implementation for circle s. If a variable has an interface type, then we can call methods that are in the named interface.
Structs and interfaces are Go's way of organizing methods and data handling. Where structs define the fields of an object, like a Person's first and last name. The interfaces define the methods; e.g. formatting and returning a Person's full name.
The idea behind go interfaces is duck typing. Which simply translates into: If you look like a duck and quack like a duck then you are a duck. Meaning that if your object implements all duck's features then there should be no problem using it as a duck. Here is an example:
package main
import (
"fmt"
)
type Walker interface {
Walk() string
}
type Human string
type Dog string
func (human Human) Walk() string { //A human is a walker
return "I'm a man and I walked!"
}
func (dog Dog) Walk() string { //A dog is a walker
return "I'm a dog and I walked!"
}
//Make a walker walk
func MakeWalk(w Walker) {
fmt.Println(w.Walk())
}
func main() {
var human Human
var dog Dog
MakeWalk(human)
MakeWalk(dog)
}
Here a Human
is a Walker
and a Dog
is a Walker
. Why? Because they both.. well... Walk
. They both implement the Walk () string
function. So this is why you can execute MakeWalk
on them.
This is very helpful when you want different types to behave in the same manner. A practical example would be file type objects (sockets, file objects) - you need a Write and a Read function on all of them. Then you can use Write and Read in the same fashion independent of their type - which is cool.
Another working example showing the interaction between an interface and a structure
package main
import "fmt"
type Info interface {
Noofchar() int
Increment()
}
type Testinfo struct {
noofchar int
}
func (x *Testinfo) Noofchar() int {
return x.noofchar
}
func (x *Testinfo) Increment() {
x.noofchar++
}
func main(){
var t Info = &Testinfo{noofchar:1}
fmt.Println("No of char ",t.Noofchar())
t.Increment()
fmt.Println("No of char ",t.Noofchar())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With