Skip to content

Latest commit

 

History

History

04

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Interfaces, defer, and panic!

In this lab, we'll be using the os and bufio packages to read our wordbank from a file on disk. Since reading a file can fail, we will also be learning the most basic error handling strategy.

  1. Add a new flag "wordbank" that accepts a filepath as a string.
  2. Modify the NewWordBank function to take an *os.File as input
  3. Create a bufio.Scanner by passing the *os.File into the bufio.NewScanner constructor.
    Note: the bufio.NewScanner function expects an io.Reader as its input. Fortunately, *os.File implements the io.Reader interface.
  4. Loop over the lines in the file and use the builtin append function to add them to your wordbank.
    Hint: see this example from the scanner documentation for inspiration.
  5. If scanner.Err() is not nil, call panic on the error value.
  6. Move the words from the old hardcoded slice into a file on disk.
  7. Modify the generateIpsum function to os.Open the file for reading
  8. If the error value returned by os.Open is not nil, call panic on the error value
  9. defer the close method on the file object immediately after handling the error.
    Hint: see this example from effective go
  10. pass the *os.File instance into the NewWordbank function.