Hi, I'm Ataias Reis

Programmer, made in Brazil, Alma mater University of Brasilia

30 days of code in Go: Day 8 - Dictionaries and Maps

Hi there! The task of today will be coding a phone book. The program reads an integer $N$ that represents the number of people in the phone book. After that, it reads the $N$ entries from standard output and generates the dictionary/map. For newbies: dictionaries are the same as maps. Java usually calls the structure with (key, value) pairs as a map, while Python calls it a dictionary. After having the phone book generated, the program will read an unknown number of names. The fact that we can query as many names as we want means that the program needs to check for an end of file before leaving, which is basically trying to read until the user cancels the program. Well, other options would be typing a special quit command, but that’s not the case for this problem.

To solve this problem, I read about maps in Go by Example: Maps and I wrote the following code:

package main

import "fmt"

// ignore err that fmt.Scanf gives
// I don't care about it here,
// but this is not actually good
// practise. Best would be to treat
// the error somehow
func scanf(name *string) bool {
  readItems, _ := fmt.Scanf("%s", name)
  return readItems > 0
}

func main() {
  // define a map
  nameToNumber := make(map[string]uint)
  // reader number of entries
  var N uint
  fmt.Scanln(&N)
  //read all entries
  var name string
  var phone uint
  for N > 0 {
    fmt.Scanf("%s %d", &name, &phone)
    nameToNumber[name] = phone
    N--
  }

  //read queries
  var queryName string

  // read until you don't find anything else
  for scanf(&queryName) {
    phone, found := nameToNumber[queryName]
    if found {
     fmt.Printf("%s=%d\n", queryName, phone)
    } else {
     fmt.Printf("Not found\n")
    }
  }
}

This program gave me more work than the one from yesterday. One the biggest problems I had was correctly using fmt.Scanf actually. The fact that it returns two values (the number of items read and an error indicator) has hindered me of just doing fmt.Scanf("%s", &queryName) != 0 like in C. Surely it is good to know that I can treat this error and it is returned, but I will not pay attention to it today. I just created a new function that wraps fmt.Scanf and ignores the error, so my loop looks neat. Below is an example with input and output:

#input (key, value)
3
ataias 1234
amanda 1235
juarez 9999
# input (query)
oi
# output
Not Found
# input
juarez
# output
juarez=9999
# input
amanda
# output
amanda=1235
# input
ataias
# output
ataias=1234
# input
juarez
# output
juarez=9999

That’s all for today! Thanks for reading!

Tags
comments powered by Disqus