Standard Library: strings and strconv
Go has a rich standard library. Here are two packages you'll use almost every time you work with text:
The strings package
strings.TrimSpace(" halo ") // "halo"
strings.ToLower("KoPi") // "kopi"
strings.ToUpper("kopi") // "KOPI"
strings.Contains("es kopi", "kopi") // true
strings.HasPrefix("INV-001", "INV-") // true
strings.Split("a,b,c", ",") // []string{"a", "b", "c"}
strings.Fields(" satu dua tiga ") // []string{"satu", "dua", "tiga"}
strings.Join([]string{"a", "b"}, "-") // "a-b"
strings.ReplaceAll("a.b.c", ".", "/") // "a/b/c"
strings.Repeat("=", 5) // "====="
A really useful function for splitting kunci=nilai (key=value) text is strings.Cut:
sebelum, sesudah, ketemu := strings.Cut("latte:2", ":")
// sebelum = "latte", sesudah = "2", ketemu = true
It returns the part before the separator, the part after it, and whether it was found. If the separator isn't found, ketemu is false.
The strconv package
strconv converts between strings and numbers:
n, err := strconv.Atoi("42") // string -> int: 42, nil
_, err = strconv.Atoi("empat") // error: invalid syntax
s := strconv.Itoa(42) // int -> string: "42"
f, err := strconv.ParseFloat("3.5", 64) // string -> float64
b, err := strconv.ParseBool("true") // string -> bool
Watch out: string(65) is not "65"; it's "A" (the character with code 65). To turn a number into its digits as text, always use strconv.Itoa or fmt.Sprint.
The Parse.../Atoi functions return an error, so handle it the way you learned in Chapter 7.
Task
A coffee shop's cashier receives orders as text like " Latte : 2 ". Complete:
parsePesanan(baris string) (string, int, error):- split the text on
:usingstrings.Cut; if there's no:, return an error, - menu item name: trim the spaces at the edges and convert it to lowercase,
- quantity: trim the spaces at the edges, then convert with
strconv.Atoi; if that fails, return an error, - if the name is empty or the quantity is
<= 0, return an error. - If an error occurs, return
"", 0, err.
- split the text on
formatStruk(nama string, jumlah int) stringreturns"<jumlah>x <NAMA HURUF BESAR>", that is, the quantity, anx, and the name in uppercase. For example,formatStruk("latte", 2)becomes"2x LATTE". Usestrconv.Itoaandstrings.ToUpper.