A Practical Example of Interfaces
This lesson provides an explanation of the use of interfaces for writing to the console by using a buffer.
We'll cover the following...
The following program is a nice illustration of the concept of interfaces in io
:
Press + to interact
package mainimport ("bufio""fmt""os")func main() {// unbuffered: os.Stdout implements io.Writerfmt.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: ...