Search⌘ K

A Practical Example of Interfaces

Explore the concept of interfaces in Go through practical examples involving io.Writer and fmt.Fprintf. Understand how different types implement the Write method and how to use buffered writing effectively. The lesson also introduces encoding methods for data transmission and storage.

We'll cover the following...

The following program is a nice illustration of the concept of interfaces in io:

Go (1.6.2)
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// unbuffered: os.Stdout implements io.Writer
fmt.Fprintf(os.Stdout, "%s\n", "hello world! - unbuffered")
// buffered:
buf := bufio.NewWriter(os.Stdout)
// and now so does buf:
fmt.Fprintf(buf, "%s\n", "hello world! - buffered")
buf.Flush()
}

Here is the actual signature of fmt.Fprintf():

func Fprintf(w io.Writer, format string, a ...interface {}) (n int, err error)

It doesn’t write to a file, it writes to a variable of type io.Writer, that is: ...