Link Search Menu Expand Document

Writing standard output and error

  • each process has stdin, a stdout and stderr file descriptors. The standard approach is the use of stdout as a process output and stderr as process error output. As these are the file descriptors, the destination where the data is written could be anything, from the console to the socket.This recipe will show you how to write the stdout and stderr.

Create the stdouterr.go file with the following content:

        package main

        import (

         func main() {

           // Simply write string
           "This is string to standard output.\n")

           "This is string to standard error output.\n")

           // Stdout/err implements
           // writer interface
           buf := []byte{0xAF, 0xFF, 0xFE}
           for i := 0; i < 200; i++ {
             if _, e := os.Stdout.Write(buf); e != nil {

           // The fmt package
           // could be used too
           fmt.Fprintln(os.Stdout, "\n")


sangam:golang-daily sangam$ go run stdouterr.go
This is string to standard output.
This is string to standard error output.

sangam:golang-daily sangam$ 

How it works…

  • As with the Stdin from the previous recipe, the Stdout and Stderr are the file descriptors. So these are implementing the Writer interface.

  • The preceding example shows a few ways of how to write into these via the io.WriteString function, with the use of the Writer API and by the fmt package and FprintXX functions.