Notes: The Go Programming Language

April 25, 2016

These are my notes from working through The Go Programming Language by Donovan and Kernighan.

Chapter 1

Exercise 1.1: Modify the echo program to also print os.Args[0], the name of the command that invoked it.

func main() {
  fmt.Println(strings.Join(os.Args[0:], " "))
}

Exercise 1.2: Modify the echo program to print the index and value of each of its arguments, one per line.

for n, x := range os.Args[1:] {
  s := strconv.Itoa(n) + ": " + x
  fmt.Println(s)
}

Exercise 1.3: Experiment to measure the difference in running time between our potentially inefficient versions and the one that uses strings.Join.

Slow version:

func main() {
  s, sep := "", ""
  for _, x := range os.Args[1:] {
    s += sep + x
    sep = " "
  }
  fmt.Println(s)
}
$ time go run main.go foo bar baz
foo bar baz

real    0m0.437s
user    0m0.480s
sys     0m0.051s

Fast version:

func main() {
  fmt.Println(strings.Join(os.Args[1:], " "))
}
$ time go run main.go foo bar baz
foo bar baz

real    0m0.503s
user    0m0.546s
sys     0m0.044s