Skip to content

Parse Commands Without Losing the Title

The Course
•
28 min study

The queue reads commands such as add 7 Review notes. Splitting on every space would break the title Review notes into two words, and the queue would have to glue them back together. The format has fixed fields first and free text last, so the parser should split only as many times as there are fixed fields.

strings.Cut splits once. Trim the line, cut off a verb and keep the remaining text for its arguments. In this command format a space separates each fixed field, while the final field can contain spaces of its own.

Predict and run

Does the title keep the space between words?

Predict, then run Go
package main

import (
	"fmt"
	"strings"
)

func main() {
	verb, rest, ok := strings.Cut(strings.TrimSpace(" add 7 Review notes "), " ")
	if !ok {
		return
	}
	id, title, ok := strings.Cut(strings.TrimSpace(rest), " ")
	if !ok {
		return
	}
	fmt.Printf("%s | %s | %s\n", verb, id, strings.TrimSpace(title))
}
Check your prediction
Text
add | 7 | Review notes

Try adding three spaces before the ID. Notice which TrimSpace handles them.

Parse an ID that fits its type

strconv.Atoi returns an int, which is 64 bits on most machines. When an ID has a narrower type, such as type TaskID int32, use strconv.ParseInt and give it the size. Its arguments are the text, the base (10 for decimal) and the bit size (32). Text for a number that does not fit returns an error, instead of silently changing value when converted. The result is still an int64, so convert it to TaskID only after the check passes. The task queue parses its IDs this way.

Parse a 32-bit ID Go
package main

import (
	"fmt"
	"strconv"
)

type TaskID int32

func parseID(text string) (TaskID, error) {
	n, err := strconv.ParseInt(text, 10, 32)
	if err != nil {
		return 0, err
	}
	return TaskID(n), nil
}

func main() {
	for _, text := range []string{"7", "2147483647", "2147483648"} {
		id, err := parseID(text)
		fmt.Println(id, err)
	}
}
Text
7 <nil>
2147483647 <nil>
0 strconv.ParseInt: parsing "2147483648": value out of range

The queue also rejects 0 and negative IDs. Where would you add that check in parseID?

Choose the action with switch

Once a line is split, the verb decides what happens: add adds, done finishes, list reports, and anything else is an error. A chain of if verb == "add" ... else if verb == "done" works, but Go has a statement made for "compare one value against several cases": switch.

Dispatch on the verb Go
package main

import (
	"fmt"
	"strings"
)

func describe(line string) string {
	verb, rest, _ := strings.Cut(strings.TrimSpace(line), " ")
	switch verb {
	case "add":
		return "adding: " + strings.TrimSpace(rest)
	case "done", "finish":
		return "finishing: " + strings.TrimSpace(rest)
	case "list":
		return "listing"
	default:
		return fmt.Sprintf("unknown command %q", verb)
	}
}

func main() {
	for _, line := range []string{"add 3 Read", "finish 3", "list", "delete 3"} {
		fmt.Println(describe(line))
	}
}
Text
adding: 3 Read
finishing: 3
listing
unknown command "delete"

Go compares verb with each case from top to bottom and runs only the first match. Unlike some languages, it never falls through into the next case, so no break is needed. One case can list several values separated by commas, as "done", "finish" does. default runs when nothing matched. Leaving it out is allowed, but in a command parser it is where unknown input gets reported, so don't. The Day 7 queue's execute is a switch on the verb with exactly this shape.

A switch with nothing after the keyword, as in switch {, is the other form: each case is a condition, and the first true one runs. It is a tidier way to write a long if/else if chain.

Practice

Exercise

Your turn

Write parse(line string) string for a small command language and make it return one line of output per command:

  • rename ID title returns rename ID to "title", keeping every space inside the title.
  • delete ID returns delete ID.
  • A known verb with a missing field returns missing field, and an unknown verb returns unknown command "verb".

The starter calls it for five lines. Once parse works, it prints:

Text
rename 5 to "Read chapter two"
delete 9
missing field
missing field
unknown command "archive"
Your working space Go
package main

import (
	"fmt"
)

func parse(line string) string {
	return ""
}

func main() {
	lines := []string{"rename 5 Read chapter two", "delete 9", "rename 5", "delete", "archive 2"}
	for _, line := range lines {
		fmt.Println(parse(line))
	}
}
Hint 1: the idea

Cut the verb off first and switch on it. Each case knows how many fields its command has: rename needs a second cut to separate the ID from the title, and delete needs only that the rest isn't empty.

Hint 2: a first step

Start with verb, rest, _ := strings.Cut(strings.TrimSpace(line), " ") and a switch verb whose default returns the unknown-command message. The last line of output should already be right. Then fill in delete, and finally rename.

Worked solution
Run the solution Go
package main

import (
	"fmt"
	"strings"
)

func parse(line string) string {
	verb, rest, _ := strings.Cut(strings.TrimSpace(line), " ")
	rest = strings.TrimSpace(rest)
	switch verb {
	case "rename":
		id, title, ok := strings.Cut(rest, " ")
		title = strings.TrimSpace(title)
		if !ok || title == "" {
			return "missing field"
		}
		return fmt.Sprintf("rename %s to %q", id, title)
	case "delete":
		if rest == "" {
			return "missing field"
		}
		return "delete " + rest
	default:
		return fmt.Sprintf("unknown command %q", verb)
	}
}

func main() {
	lines := []string{"rename 5 Read chapter two", "delete 9", "rename 5", "delete", "archive 2"}
	for _, line := range lines {
		fmt.Println(parse(line))
	}
}
Text
rename 5 to "Read chapter two"
delete 9
missing field
missing field
unknown command "archive"

rename 5 has an ID but no title, so the second cut finds no space and ok is false. delete alone cuts to an empty rest. The first strings.Cut ignores its ok result on purpose: a line with no space is just a verb with nothing after it, and each case decides whether that is enough. strings.Fields would have broken Read chapter two into three words.

Was this article helpful?

Your response is saved on this device.