Briefing on interfaces in Go

Go's interfacing system is different from the interfacing systems in other languages. They are named collections of methods. Interfaces are important in composing readable Go code because they make the code scalable and flexible. Interfaces also give us the ability to have polymorphism (providing a single interface to items with different types) in Go. Another positive aspect of interfaces is that they are implicitly implemented—the compiler checks that a specific type implements a specific interface. 

We can define an interface as follows:

type example interface {
foo() int
bar() float64
}

If we want to implement an interface, all we need to do is implement the methods that are referenced in the interface. The compiler validates your interface's methods so that you don't have to perform this action.

We can also define an empty interface, which is an interface that has zero methods, represented by interface{}. Empty interfaces are valuable and practical in Go, as we can pass arbitrary values to them, as shown in the following code block:

package main
import "fmt"
func main() {
var x interface{}
x = "hello Go"
fmt.Printf("(%v, %T) ", x, x)
x = 123
fmt.Printf("(%v, %T) ", x, x)
x = true
fmt.Printf("(%v, %T) ", x, x)
}

As we execute our empty interface example, we can see that the type and value of the x interface change as we change the definition of the (initially) empty interface:

Empty, mutable interfaces are convenient because they give us the flexibility to manipulate our data in a way that makes sense to the code composer. 

In the next section, we will discuss comprehending methods in Go.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.82.244