Go: A task list

A command loop over a list is the pattern behind many real tools.

What to build

A program that manages a list of tasks from commands, like the one in the lesson.

Requirements

  • Read lines until the input ends. Skip empty lines. Tasks are numbered 1, 2, 3 in the order they are added.
  • add TEXT adds a task and prints added N. done N marks task N finished, or prints no task N when it does not exist.
  • list prints each task as [ ] N TEXT or [x] N TEXT when finished. count prints open: A, done: B.
  • Any other command prints unknown command: WORD.

Input

Any number of command lines.

Output

Messages as described.

Constraints

Up to 100 lines; the text of a task has at most 50 characters; N is a whole number.

Example

Input:

add buy milk
add write the report
done 1
list
count

Output:

added 1
added 2
[x] 1 buy milk
[ ] 2 write the report
open: 1, done: 1

Why it works

The task keeps its number, text and state in one struct. A loop over the commands with a switch makes the program easy to extend with new commands.

Examples

Example 1 · Input
add buy milk
add write the report
done 1
list
count
Expected output
added 1
added 2
[x] 1 buy milk
[ ] 2 write the report
open: 1, done: 1
Example 2 · Input
done 3
add one
done 2
count
dance
Expected output
no task 3
added 1
no task 2
open: 1, done: 0
unknown command: dance

Hints

Hint 1

Keep a slice of struct values with ID, Text and Done, and read lines with bufio.Scanner.

Hint 2

For add, join fields[1:] with a space; for done, convert fields[1] with strconv.Atoi and search the slice.

Solution

Show one correct solution (try it yourself first)
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type Task struct {
	ID   int
	Text string
	Done bool
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	tasks := []Task{}
	for scanner.Scan() {
		fields := strings.Fields(scanner.Text())
		if len(fields) == 0 {
			continue
		}
		switch fields[0] {
		case "add":
			tasks = append(tasks, Task{len(tasks) + 1, strings.Join(fields[1:], " "), false})
			fmt.Println("added", len(tasks))
		case "done":
			id := 0
			if len(fields) > 1 {
				id, _ = strconv.Atoi(fields[1])
			}
			if id < 1 || id > len(tasks) {
				fmt.Println("no task", fields[len(fields)-1])
			} else {
				tasks[id-1].Done = true
			}
		case "list":
			for _, t := range tasks {
				mark := " "
				if t.Done {
					mark = "x"
				}
				fmt.Printf("[%s] %d %s\n", mark, t.ID, t.Text)
			}
		case "count":
			open, done := 0, 0
			for _, t := range tasks {
				if t.Done {
					done++
				} else {
					open++
				}
			}
			fmt.Printf("open: %d, done: %d\n", open, done)
		default:
			fmt.Println("unknown command:", fields[0])
		}
	}
}

▶ Open this solution in the compiler

Lesson: Putting it together: a command-line program →