map of list of strings

This is an example Go program which makes a map to a list of strings.

The input looks like this:

fish: puffer pike cod
mammals: dolphin
characters: Mario Luigi

package main

import (
        "bufio"
        "fmt"
        "os"
        "log"
        "math/rand"
)

func main() {
        stuff := make (map[string] []string)
        input, err := os.Open("input.txt")
        if err != nil {
                log.Fatal(err)
        }
        scanner := bufio.NewScanner(input)
        for scanner.Scan() {
                line := scanner.Text()
                var key string
                end := -1
                for pos, char := range line {
                        switch char {
                        case ':':
                                key = line[:pos]
                                stuff[key] = make([]string, 0)
                        case ' ':
                                if end != -1 {
                                        stuff[key] = append(stuff[key], line[end:pos])
                                }
                                end = pos + 1
                        }
                }
                if end != -1 {
                        stuff[key] = append(stuff[key], line[end:])
                }
        }
        character := stuff["characters"][rand.Intn(len(stuff["characters"]))]
        fish := stuff["fish"][rand.Intn(len(stuff["fish"]))]
        fmt.Printf ("%s eats %s\n", character, fish)
}

(download)

The output of the example looks like this:

Luigi eats puffer


Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer