Some examples

The previous program reads a file in its entirety, but a more common scenario is thatyou want to read a file on a line-by-line basis. The following snippet shows a wayto do just that (we’re discarding the error returned from os.Open here to keepthe examples smaller – don’t ever do this in real life code).

  1. f, _ := os.Open("/etc/passwd"); defer f.Close()
  2. r := bufio.NewReader(f) 1
  3. s, ok := r.ReadString('\n') 2

At 1 make f a bufio to have access to the ReadString method. Then at 2 we reada line from the input, s now holds a string which we can manipulate with, for instance,the strings package.

A more robust method (but slightly more complicated) is ReadLine, see the documentationof the bufio package.

A common scenario in shell scripting is that you want to check if a directoryexists and if not, create one.

  1. if [ ! -e name ]; then if f, e := os.Stat("name"); e != nil {
  2. mkdir name os.Mkdir("name", 0755)
  3. else } else {
  4. # error // error
  5. fi }

The similarity between these two examples (and with other scripting languages)have prompted comments that Go has a “script”-like feel to it, i.e. programmingin Go can be compared to programming in an interpreted language (Python, Ruby,Perl or PHP).