Updating the phone book application
In this last section of the book, we are going to create a function that populates the phone book application from the previous chapter with random data, which is pretty handy when you want to put lots of data in an application for testing purposes.
I have used this handy technique in the past in order to put sample data on Kafka topics.
The biggest change in this version of the phone book application is that the searching is based on the telephone number because it is easier to search random numbers instead of random strings. But this is a small code change in the search()
function—this time search()
uses v.Tel == key
instead of v.Surname == key
in order to try to match the Tel
field.
The populate()
function of phoneBook.go
(as found in the ch02
directory) does all the work—the implementation of populate()
is the following.
func populate(n int, s []Entry) {
for i := 0; i < n; i++ {
name := getString(4)
surname := getString(5)
n := strconv.Itoa(random(100, 199))
data = append(data, Entry{name, surname, n})
}
}
The getString()
function generates letters from A
to Z
and nothing else in order to make the generated strings more readable. There is no point in using special characters in names and surnames. The generated telephone numbers are in the 100 to 198 range, which is implemented using a call to random(100, 199)
. The reason for this is that it is easier to search for a three-digit number. Feel free to experiment with the generated names, surnames, and telephone numbers.
Working with phoneBook.go
generates the following kind of output:
$ go run phoneBook.go search 123
Data has 100 entries.
{BHVA QEEQL 123}
$ go run phoneBook.go search 1234
Data has 100 entries.
Entry not found: 1234
$ go run phoneBook.go list
Data has 100 entries.
{DGTB GNQKI 169}
{BQNU ZUQFP 120}
...
Although these randomly generated names and surnames are not perfect, they are more than enough for testing purposes. In the next chapter, we'll learn how to work with CSV data.