SyntaxPilot
Courses/Go Programming/Lesson 37
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 37 of 89

Standard library tour: strconv, sort, math, regexp, templates, containers

strconv (Atoi, Itoa, ParseInt, ParseFloat, FormatInt, Quote)sort.Slicesort.Interfaceslices.SortFuncmathmath/bigmath/rand/v2crypto/randregexp (RE2 syntax, no backtracking)text/templatehtml/templatecontainer/heapcontainer/listcontainer/ring

These are the notes for Go episode 37. Raju's shop now takes orders online, and each day brings a new problem. Quantities arrive from the form as text, so "12" + "3" gives "123". Prices sorted as text put 1200 before 45. 0.1 + 0.2 is not 0.3, and 25! silently overflows an int64. OTPs from a fixed seed repeat on every run, a length check accepts 98765abcde as a phone number, a review containing <script> would run in every visitor's browser, and re-sorting a queue of 80,000 orders takes five seconds. Each time, the obvious fix fails, and you find the package Go already ships for the job: strconv, sort and slices, math and math/big, math/rand/v2 and crypto/rand, regexp, text/template and html/template, container/heap, container/list, container/ring and unicode/utf8.

The standard library is the set of packages that comes with Go itself: you import them, with nothing to download.

Every program here runs as-is in the SyntaxPilot compiler (language: Go) with go run main.go. All outputs and errors are from real runs (Go 1.24.7, linux/amd64). Programs that use random numbers or timings print different values on every run; this is marked under their output.

Facts and sources

From the standard library documentation shipped with Go 1.24.7 (go doc <package>):

  • strconv.Atoi "is equivalent to ParseInt(s, 10, 0), converted to type int." ParseInt takes a base (0, 2 to 36) and a bit size (0, 8, 16, 32, 64 for int, int8 … int64).
  • regexp: the syntax "is the syntax accepted by RE2", and "The regexp implementation provided by this package is guaranteed to run in time linear in the size of the input. (This is a property not guaranteed by most open source implementations of regular expressions.)"
  • math/rand/v2: "implements pseudo-random number generators suitable for tasks such as simulation, but it should not be used for security-sensitive work." "This package's outputs might be easily predictable regardless of how it's seeded. For random numbers suitable for security-sensitive work, see the crypto/rand package."
  • crypto/rand.Text "returns a cryptographically random string using the standard RFC 4648 base32 alphabet ... The result contains at least 128 bits of randomness". It was added in Go 1.24; math/rand/v2 in Go 1.22; slices, cmp and cmp.Compare in Go 1.21 (from the API lists api/go1.*.txt shipped with Go).

The problem: numbers that arrive as text

A web form always sends text. Adding two strings joins them:

package main

import "fmt"

func main() {
    // quantities typed into Raju's order form arrive as text
    qty1, qty2 := "12", "3"
    fmt.Println("total:", qty1+qty2)
}

Output:

total: 123

The obvious fix, converting with int(...) as in episode 4, does not compile:

package main

import "fmt"

func main() {
    // quantities typed into Raju's order form arrive as text
    qty1, qty2 := "12", "3"
    fmt.Println("total:", qty1+qty2)
    fmt.Println("as int:", int(qty1))
}

Output:

# command-line-arguments
./main.go:9:32: cannot convert qty1 (variable of type string) to type int

A conversion (T(x)) only changes how a value of a compatible type is stored. Text is not stored as a number, and int("hello") would make no sense, so reading digits out of text is parsing: a function that reads text and can fail, so it returns an error.

strconv: text ↔ numbers (the bank clerk)

A bank clerk reads the amount written on a cheque into the ledger (parse), returns the cheque if the amount is unreadable (error), and prints the number back on the receipt (format). strconv ("string conversions") does exactly this:

Clerk Go Can fail?
reads "12" into the ledger strconv.Atoi("12") → 12, nil yes: returns (int, error)
rejects "twelve-ish" err is strconv.Atoi: parsing ...: invalid syntax —
prints 1042 on the receipt strconv.Itoa(1042) → "1042" no: returns just a string

Atoi means "ASCII to integer", Itoa "integer to ASCII".

package main

import (
    "fmt"
    "strconv"
)

func main() {
    a, err := strconv.Atoi("12")
    b, _ := strconv.Atoi("3")
    fmt.Println(a+b, err)
    fmt.Println("bill no " + strconv.Itoa(1042))

    _, err = strconv.Atoi("12a")
    fmt.Println(err)
    _, err = strconv.ParseInt("300", 10, 8)
    fmt.Println(err)
}

Output:

15 <nil>
bill no 1042
strconv.Atoi: parsing "12a": invalid syntax
strconv.ParseInt: parsing "300": value out of range
  • A nil error means "no error".
  • ParseInt(s, base, bitSize): the base is the number system (10 decimal, 16 hexadecimal, 2 binary); the bit size is the integer size the result must fit in. int8 holds −128 to 127, so "300" is out of range.
  • The error is a *strconv.NumError; errors.Is(err, strconv.ErrSyntax) and errors.Is(err, strconv.ErrRange) tell the two cases apart (episode 25).

More of the package:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    n, _ := strconv.ParseInt("ff", 16, 64)
    f, _ := strconv.ParseFloat("249.50", 64)
    ok, _ := strconv.ParseBool("true")
    fmt.Println(n, f, ok)

    fmt.Println(strconv.FormatInt(255, 2), strconv.FormatInt(255, 16))
    fmt.Println(strconv.FormatFloat(249.5, 'f', 2, 64))
    fmt.Println(strconv.Quote("Raju said \"hi\"\n"))
    fmt.Println(string(rune(65)), strconv.Itoa(65))
}

Output:

255 249.5 true
11111111 ff
249.50
"Raju said \"hi\"\n"
A 65
Function Does Example
ParseInt(s, base, bits) text → int64 in any base ParseInt("ff", 16, 64) = 255
ParseFloat(s, bits) text → float64 ParseFloat("249.50", 64) = 249.5
ParseBool(s) "true", "1", "false", "0" … → bool true
FormatInt(n, base) int64 → text in any base FormatInt(255, 2) = "11111111"
FormatFloat(f, 'f', 2, 64) float → text with 2 decimals "249.50"
Quote(s) add quotes and escape special characters "\"hi\"\n"
Itoa(n) int → decimal text "65"

Trap: string(rune(65)) is "A", the character with code 65, not the digits "65". (Writing string(65) with an int compiles, but go vet warns "conversion from int to string yields a string of one rune, not a string of digits".) For digits, use strconv.Itoa.

Sorting: sort and slices (the teacher lining up students)

Strings sort lexicographically, character by character like a dictionary, so "1200" comes before "45" because '1' < '4':

package main

import (
    "fmt"
    "sort"
)

func main() {
    prices := []string{"90", "250", "1200", "45"}
    sort.Strings(prices) // text sorts letter by letter
    fmt.Println(prices)

    nums := []int{90, 250, 1200, 45}
    sort.Ints(nums)
    fmt.Println(nums)
}

Output:

[1200 250 45 90]
[45 90 250 1200]

Parse first, then sort numbers.

sort.Slice with a less function

Real data is structs. sort.Slice(x, less) takes the slice and a less function: less(i, j) returns true when element i must come before element j.

package main

import (
    "fmt"
    "sort"
)

type Order struct {
    ID     int
    Amount int
}

func main() {
    orders := []Order{{1, 250}, {2, 90}, {3, 1200}, {4, 90}}
    sort.Slice(orders, func(i, j int) bool {
        return orders[i].Amount > orders[j].Amount // biggest first
    })
    fmt.Println(orders)
}

Output:

[{3 1200} {1 250} {2 90} {4 90}]

sort.Slice is not stable: equal items (the two 90s) may end up in any order. A stable sort keeps equal items in their original order, which matters when you sort by one key after another; use sort.SliceStable or slices.SortStableFunc.

The slices package (episode 14) works with any slice type through generics. Its compare function returns a negative number, zero or a positive number (a < b, a == b, a > b), and cmp.Compare computes that for any ordered type.

package main

import (
    "cmp"
    "fmt"
    "slices"
)

type Order struct {
    ID     int
    Amount int
}

func main() {
    orders := []Order{{1, 250}, {2, 90}, {3, 1200}, {4, 90}}
    slices.SortStableFunc(orders, func(a, b Order) int {
        return cmp.Compare(a.Amount, b.Amount) // smallest first
    })
    fmt.Println(orders)
    i, found := slices.BinarySearchFunc(orders, 250, func(o Order, t int) int {
        return cmp.Compare(o.Amount, t)
    })
    fmt.Println(i, found)
}

Output:

[{2 90} {4 90} {1 250} {3 1200}]
2 true

Binary search halves the search range at every step, so it finds an item among a million in about 20 steps — but only in sorted data. BinarySearchFunc returns the index where the item is (or would be inserted) and whether it was found.

sort.Interface: Len, Less, Swap

The oldest API: any type with the three methods Len() int, Less(i, j int) bool and Swap(i, j int) satisfies sort.Interface and can be sorted by sort.Sort. sort.Reverse wraps it and flips Less.

package main

import (
    "fmt"
    "sort"
)

type ByAmount []int // a defined type with 3 methods

func (s ByAmount) Len() int           { return len(s) }
func (s ByAmount) Less(i, j int) bool { return s[i] < s[j] }
func (s ByAmount) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

func main() {
    bills := ByAmount{250, 90, 1200, 45}
    sort.Sort(bills) // sort.Interface: Len, Less, Swap
    fmt.Println(bills, sort.IsSorted(bills))
    sort.Sort(sort.Reverse(bills))
    fmt.Println(bills)
}

Output:

[45 90 250 1200] true
[1200 250 90 45]
Way Use when
slices.Sort(xs) a slice of numbers or strings
slices.SortFunc / SortStableFunc + cmp.Compare structs, new code
sort.Slice / sort.SliceStable older code bases
sort.Interface + sort.Sort a type that already has Len/Less/Swap; also the basis of container/heap

math, floats and math/big

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(math.Sqrt(144), math.Pow(2, 10), math.Abs(-7.5))
    fmt.Println(math.Floor(2.7), math.Ceil(2.1), math.Round(2.5))
    fmt.Println(math.Max(3, 9), math.Min(3, 9))
    fmt.Println(math.MaxInt64, math.Pi)
    fmt.Println(math.Inf(1), math.NaN(), math.IsNaN(math.NaN()))
    a, b := 0.1, 0.2 // float64 variables
    fmt.Println(a+b == 0.3, a+b)
}

Output:

12 1024 7.5
2 3 3
9 3
9223372036854775807 3.141592653589793
+Inf NaN true
false 0.30000000000000004
  • math.Round(2.5) rounds half away from zero: 3. math.Floor rounds down, math.Ceil up.
  • math.Inf(1) is +∞; NaN ("not a number") is the result of undefined operations like 0/0 on floats; check it with math.IsNaN, because NaN == NaN is false.
  • 0.1 + 0.2 != 0.3: a float64 stores numbers in binary, and 0.1 has no exact binary form, just as 1/3 has no exact decimal form. (With constants, 0.1+0.2 == 0.3 is true, because untyped constants are exact, from episode 5. The surprise appears with variables.)
  • So keep money as integer paise in an int.

Integers have a limit. 25! (factorial: 1 × 2 × … × 25) does not fit in an int64, and Go wraps around silently on overflow (episode 4):

package main

import "fmt"

func main() {
    // ways to arrange 25 delivery stops: 25! (factorial)
    f := int64(1)
    for i := int64(1); i <= 25; i++ {
        f *= i
    }
    fmt.Println("25! =", f)
}

Output:

25! = 7034535277573963776

The real 25! has 26 digits; the maximum int64 is 9,223,372,036,854,775,807 (about 9.2 × 10¹⁸). The fix is math/big, whose numbers grow to any size:

package main

import (
    "fmt"
    "math/big"
)

func main() {
    f := big.NewInt(1)
    for i := int64(1); i <= 25; i++ {
        f.Mul(f, big.NewInt(i)) // f = f * i, no overflow
    }
    fmt.Println("25! =", f)

    a, _ := new(big.Int).SetString("99999999999999999999", 10)
    fmt.Println(a.Add(a, big.NewInt(1)))
    r := big.NewRat(1, 10)
    r.Add(r, big.NewRat(2, 10))
    fmt.Println(r, r.Cmp(big.NewRat(3, 10)) == 0)
}

Output:

25! = 15511210043330985984000000
100000000000000000000
3/10 true
  • Methods store the result in the receiver: f.Mul(f, x) means f = f * x, and return it so calls can chain.
  • new(big.Int).SetString(s, 10) reads a number of any length from text.
  • big.Rat holds exact fractions; big.Float holds floats with chosen precision.
  • Cost: big numbers are much slower than int. Use them for cryptography, exact finance maths and huge counts, not everywhere.

Random numbers: math/rand/v2 and crypto/rand

Real life Go For
a lucky draw at the fair math/rand/v2 games, simulations, shuffling
a bank locker key crypto/rand passwords, tokens, OTPs, keys
a dealer who always shuffles the same way a fixed seed reproducible tests only

A pseudo-random generator computes numbers with a formula that only look random. It starts from a seed; the same seed gives the same sequence. PCG is one of the generator formulas in math/rand/v2.

package main

import (
    "fmt"
    "math/rand/v2"
)

func main() {
    // OTP for a customer, from a generator with a fixed seed
    r := rand.New(rand.NewPCG(2026, 11))
    for i := 0; i < 3; i++ {
        fmt.Printf("OTP %06d\n", r.IntN(1_000_000))
    }
}

Output:

OTP 366339
OTP 334146
OTP 930946

Run it again and you get exactly the same three OTPs: anyone who knows the seed knows every OTP.

The fix:

package main

import (
    crand "crypto/rand"
    "fmt"
    "math/big"
    "math/rand/v2"
)

func main() {
    // fine for games and lucky draws: math/rand/v2
    fmt.Println("winner:", rand.IntN(100)+1) // 1 to 100
    fmt.Println("shuffled:", rand.Perm(5))

    // secrets: crypto/rand reads the operating system
    n, err := crand.Int(crand.Reader, big.NewInt(1_000_000))
    fmt.Printf("OTP %06d %v\n", n, err)
    fmt.Println("token:", crand.Text())
}

Output (one real run; the values change on every run):

winner: 97
shuffled: [2 0 4 3 1]
OTP 032168 <nil>
token: IATJCHXFKEO4YKN4ANQKNNYRZG
  • Top-level functions like rand.IntN(n) (0 to n−1) and rand.Perm(n) use a randomly seeded generator: fine for games.
  • crypto/rand reads randomness gathered by the operating system. crand.Int(crand.Reader, max) gives a uniform number below max; crand.Text() gives a secret token with at least 128 bits of randomness.
  • Both packages are called rand, so one gets an import alias (crand, episode 27).
  • The old math/rand (v1) still exists; new code should use math/rand/v2.

regexp: describing the shape of text

A length check is not a phone check:

package main

import (
    "fmt"
    "strings"
)

func main() {
    // is it a valid 10-digit Indian mobile number?
    for _, p := range []string{"9876543210", "98765", "98765abcde"} {
        ok := len(p) == 10 && !strings.Contains(p, " ")
        fmt.Println(p, ok)
    }
}

Output:

9876543210 true
98765 false
98765abcde true

A regular expression (regex) is a small pattern language that describes the shape of text.

Piece Means Example
^ / $ start / end of the text ^abc$ matches only "abc"
[6-9] one character from 6 to 9 7
[0-9] or \d one digit 4
{9} exactly 9 of the previous [0-9]{9}
+, *, ? one or more, zero or more, optional a+
(...) capture group: a part you want back PIN (\d{6})
. any character a.c
package main

import (
    "fmt"
    "regexp"
)

var mobile = regexp.MustCompile(`^[6-9][0-9]{9}$`)

func main() {
    tests := []string{"9876543210", "98765", "98765abcde", "1234567890"}
    for _, p := range tests {
        fmt.Println(p, mobile.MatchString(p))
    }
    msg := "Call 9876543210 or 9123456780 today"
    digits := regexp.MustCompile(`[6-9][0-9]{9}`)
    fmt.Println(digits.FindAllString(msg, -1))
    fmt.Println(digits.ReplaceAllString(msg, "XXXXXXXXXX"))
}

Output:

9876543210 true
98765 false
98765abcde false
1234567890 false
[9876543210 9123456780]
Call XXXXXXXXXX or XXXXXXXXXX today
  • regexp.MustCompile compiles a pattern into a *Regexp and panics if the pattern is invalid: use it for fixed patterns in package variables. regexp.Compile returns an error instead.
  • Write patterns in raw strings (backquotes, episode 17) so backslashes stay as they are.
  • MatchString, FindString, FindAllString(s, -1) (−1 = all matches), ReplaceAllString, FindStringSubmatch (match + groups).
package main

import (
    "fmt"
    "regexp"
)

func main() {
    pin := regexp.MustCompile(`PIN (\d{6})`)
    m := pin.FindStringSubmatch("Deliver to PIN 110001, Delhi")
    fmt.Printf("%q\n", m)

    _, err := regexp.Compile(`a(?=b)`) // lookahead
    fmt.Println(err)
    _, err = regexp.Compile(`[0-9`)
    fmt.Println(err)
}

Output:

["PIN 110001" "110001"]
error parsing regexp: invalid or unsupported Perl syntax: `(?=`
error parsing regexp: missing closing ]: `[0-9`

RE2 is the regex syntax Go uses. It has no backtracking (trying one path, going back and trying another), so it leaves out features like lookahead (?=...) and backreferences \1, and in return Go guarantees matching runs in linear time: twice the input, at most about twice the work. Backtracking engines can take minutes on a pathological pattern, which is a known way to freeze servers.

text/template and html/template (the wedding card)

A wedding card is printed once with blanks ("Dear ____") and filled for each guest. A template is text with actions in double braces, filled from data.

Action Means
{{.}} the current data ("dot")
{{.Name}} the field Name of the data
{{range .Items}} ... {{end}} repeat for each item; inside, . is the item
{{if gt .Total 500}} ... {{end}} condition; gt = greater than (lt, eq, ne, le, ge)
package main

import (
    "os"
    "text/template"
)

type Bill struct {
    Name  string
    Items []string
    Total int
}

const receipt = `Dear {{.Name}},
{{range .Items}}- {{.}}
{{end}}Total: Rs {{.Total}}{{if gt .Total 500}} (free delivery){{end}}
`

func main() {
    t := template.Must(template.New("r").Parse(receipt))
    t.Execute(os.Stdout, Bill{"Asha", []string{"chai", "samosa"}, 620})
}

Output:

Dear Asha,
- chai
- samosa
Total: Rs 620 (free delivery)
  • template.Must panics if parsing fails; Execute(w, data) writes the result to any io.Writer (here standard output).
  • Errors in data access happen at Execute time:
package main

import (
    "os"
    "text/template"
)

func main() {
    t := template.Must(template.New("r").Parse("Total: {{.Totl}}\n"))
    err := t.Execute(os.Stdout, struct{ Total int }{620})
    os.Stdout.WriteString(err.Error() + "\n")
}

Output:

Total: template: r:1:9: executing "r" at <.Totl>: can't evaluate field Totl in type struct { Total int }

Escaping: html/template

A customer's review contains a <script> tag. In a web page, text/template would insert it raw and every visitor's browser would run it: cross-site scripting (XSS). html/template escapes it, turning < into &lt; so the browser shows the text instead of running it.

package main

import (
    htmpl "html/template"
    "os"
    "text/template"
)

func main() {
    review := `<script>alert("hacked")</script>`
    page := "<p>Review: {{.}}</p>\n"

    t := template.Must(template.New("t").Parse(page))
    t.Execute(os.Stdout, review) // text/template: raw

    h := htmpl.Must(htmpl.New("h").Parse(page))
    h.Execute(os.Stdout, review) // html/template: escaped
}

Output:

<p>Review: <script>alert("hacked")</script></p>
<p>Review: &lt;script&gt;alert(&#34;hacked&#34;)&lt;/script&gt;</p>

Rule: for HTML, always html/template. It has the same API and understands context (HTML, attributes, JavaScript, URLs).

container/heap, container/list, container/ring

Real life Go Structure
hospital emergency desk: most serious first container/heap priority queue
train coaches: unhook or add anywhere container/list doubly linked list
delivery boys taking turns container/ring circular list

Re-sorting the whole queue for every new order is wasted work:

package main

import (
    "fmt"
    "slices"
    "time"
)

func main() {
    // urgent orders first: re-sort the whole queue on every new order
    start := time.Now()
    queue := []int{}
    for i := 0; i < 80_000; i++ {
        queue = append(queue, (i*7919)%80_000)
        slices.Sort(queue) // sorts everything, every single time
    }
    fmt.Println("most urgent:", queue[len(queue)-1])
    fmt.Println("took:", time.Since(start).Round(time.Second))
}

Output (one real run; the values change on every run):

most urgent: 79999
took: 4s

A heap is a binary tree stored in a slice where every parent beats its children, so the best item is always at index 0. heap.Push and heap.Pop cost about log n steps (17 steps for 80,000 items) instead of re-sorting everything. A priority queue is a queue that always hands out the highest-priority item first.

container/heap needs sort.Interface (Len, Less, Swap) plus Push(x any) and Pop() any:

package main

import (
    "container/heap"
    "fmt"
    "time"
)

type PQ []int // max-heap: the biggest number on top

func (h PQ) Len() int           { return len(h) }
func (h PQ) Less(i, j int) bool { return h[i] > h[j] }
func (h PQ) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *PQ) Push(x any)        { *h = append(*h, x.(int)) }
func (h *PQ) Pop() any {
    old := *h
    x := old[len(old)-1]
    *h = old[:len(old)-1]
    return x
}

func main() {
    start := time.Now()
    h := &PQ{}
    for i := 0; i < 80_000; i++ {
        heap.Push(h, (i*7919)%80_000)
    }
    fmt.Println("most urgent:", (*h)[0])
    fmt.Println("fast:", time.Since(start) < 100*time.Millisecond)
    fmt.Println("next:", heap.Pop(h), heap.Pop(h), heap.Pop(h))
}

Output:

most urgent: 79999
fast: true
next: 79999 79998 79997
  • Less with > makes a max-heap (biggest first); with < a min-heap.
  • Always call heap.Push(h, x) / heap.Pop(h), never your own h.Push / h.Pop directly: the package functions restore the heap order.
package main

import (
    "container/list"
    "container/ring"
    "fmt"
)

func main() {
    l := list.New() // doubly linked list
    l.PushBack("chai")
    l.PushBack("samosa")
    l.PushFront("water")
    for e := l.Front(); e != nil; e = e.Next() {
        fmt.Print(e.Value, " ")
    }
    fmt.Println(l.Len())

    r := ring.New(3) // a circle: delivery boys take turns
    for _, n := range []string{"Ravi", "Amit", "Sunil"} {
        r.Value = n
        r = r.Next()
    }
    for i := 0; i < 5; i++ {
        fmt.Print(r.Value, " ")
        r = r.Next()
    }
    fmt.Println()
}

Output:

water chai samosa 3
Ravi Amit Sunil Ravi Amit 
  • A linked list element knows the elements before and after it, so inserting at the front or back is instant; walk it with Front() and Next().
  • A ring is a circular list: after the last element comes the first again.
  • Value has type any, so you need type assertions (episode 22). In practice slices are faster for most jobs.

unicode/utf8

Text in Go is UTF-8 (episode 17), where one character (a rune) takes 1 to 4 bytes.

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    name := "Café ☕"
    fmt.Println(len(name), utf8.RuneCountInString(name))
    r, size := utf8.DecodeRuneInString("☕ hot")
    fmt.Println(string(r), size, utf8.RuneLen('é'))
    fmt.Println(utf8.ValidString(name), utf8.ValidString("\xff"))
}

Output:

9 6
☕ 3 2
true false

len counts bytes (9), utf8.RuneCountInString counts characters (6). ValidString rejects broken UTF-8 such as a lone \xff byte.

Mini project: Raju's order desk

Read lines id,phone,amount,priority; parse each number with strconv and report bad lines; reject phones that don't match ^[6-9][0-9]{9}$; serve orders by priority with container/heap; print each receipt with text/template and a fresh OTP from crypto/rand.

Solution
package main

import (
    "container/heap"
    crand "crypto/rand"
    "fmt"
    "math/big"
    "os"
    "regexp"
    "strconv"
    "strings"
    "text/template"
)

type Order struct {
    ID, Amount, Priority int
    Phone                string
    OTP                  string
}

type Queue []Order

func (q Queue) Len() int           { return len(q) }
func (q Queue) Less(i, j int) bool { return q[i].Priority > q[j].Priority }
func (q Queue) Swap(i, j int)      { q[i], q[j] = q[j], q[i] }
func (q *Queue) Push(x any)        { *q = append(*q, x.(Order)) }
func (q *Queue) Pop() any {
    old := *q
    x := old[len(old)-1]
    *q = old[:len(old)-1]
    return x
}

var mobile = regexp.MustCompile(`^[6-9][0-9]{9}$`)

var receipt = template.Must(template.New("r").Parse(
    "Order {{.ID}} (priority {{.Priority}}) to {{.Phone}}: Rs {{.Amount}}, OTP {{.OTP}}\n"))

func otp() string {
    n, err := crand.Int(crand.Reader, big.NewInt(1_000_000))
    if err != nil {
        panic(err)
    }
    return fmt.Sprintf("%06d", n)
}

func main() {
    lines := []string{
        "41,9876543210,250,2",
        "42,98765,90,5",
        "43,9123456780,12a,1",
        "44,7012345678,1200,9",
    }
    q := &Queue{}
    for _, l := range lines {
        f := strings.Split(l, ",")
        id, err1 := strconv.Atoi(f[0])
        amount, err2 := strconv.Atoi(f[2])
        prio, err3 := strconv.Atoi(f[3])
        if err1 != nil || err2 != nil || err3 != nil {
            fmt.Println("bad line:", l)
            continue
        }
        if !mobile.MatchString(f[1]) {
            fmt.Println("bad phone in order", id)
            continue
        }
        heap.Push(q, Order{ID: id, Amount: amount, Priority: prio, Phone: f[1]})
    }
    for q.Len() > 0 {
        o := heap.Pop(q).(Order)
        o.OTP = otp()
        receipt.Execute(os.Stdout, o)
    }
}

Output (one real run; the values change on every run):

bad phone in order 42
bad line: 43,9123456780,12a,1
Order 44 (priority 9) to 7012345678: Rs 1200, OTP 058433
Order 41 (priority 2) to 9876543210: Rs 250, OTP 909360

Common mistakes (and the real messages)

Mistake Real message / result Why Fix
"12" + "3" 123 + joins strings parse first
int(qty1) on a string cannot convert qty1 (variable of type string) to type int text needs parsing strconv.Atoi(qty1)
ignoring Atoi's error strconv.Atoi: parsing "12a": invalid syntax parsing can fail if err != nil { ... }
ParseInt("300", 10, 8) strconv.ParseInt: parsing "300": value out of range int8 is −128..127 a bigger bit size
string(rune(65)) for "65" A a rune conversion strconv.Itoa(65)
sorting numbers as strings [1200 250 45 90] dictionary order parse, then sort
0.1+0.2 == 0.3 with floats false (0.30000000000000004) binary floats integer paise, math/big
25! in an int64 7034535277573963776 silent overflow math/big
OTP from math/rand same OTPs every run (fixed seed), predictable not for security crypto/rand
lookahead in a Go regexp error parsing regexp: invalid or unsupported Perl syntax:(?=`` RE2 has no backtracking match, then check in code
a missing ] error parsing regexp: missing closing ]:[0-9`` broken pattern fix the pattern
misspelled template field can't evaluate field Totl in type struct { Total int } no such field check names; test templates
user text in text/template HTML script runs (XSS) no escaping html/template
calling h.Pop() directly heap order broken skips the heap logic heap.Pop(h)

Practice

  1. (Homework) Build the order desk (solution above).
  2. (Homework) Sort orders by amount, and by ID when the amounts are equal.
  3. (Homework) Validate Indian PIN codes with a regexp: 6 digits, not starting with 0.
  4. (Homework) Compute 50! with math/big. How many digits does it have?
Solution 2
package main

import (
    "cmp"
    "fmt"
    "slices"
)

type Order struct{ ID, Amount int }

func main() {
    orders := []Order{{4, 90}, {1, 250}, {3, 90}, {2, 1200}}
    slices.SortFunc(orders, func(a, b Order) int {
        if c := cmp.Compare(a.Amount, b.Amount); c != 0 {
            return c
        }
        return cmp.Compare(a.ID, b.ID) // tie: smaller ID first
    })
    fmt.Println(orders)
}

Output:

[{3 90} {4 90} {1 250} {2 1200}]
Solution 3
package main

import (
    "fmt"
    "regexp"
)

// Indian PIN codes: 6 digits, the first is 1 to 9
var pin = regexp.MustCompile(`^[1-9][0-9]{5}$`)

func main() {
    for _, p := range []string{"110001", "560034", "011001", "12345", "1100011"} {
        fmt.Println(p, pin.MatchString(p))
    }
}

Output:

110001 true
560034 true
011001 false
12345 false
1100011 false
Solution 4
package main

import (
    "fmt"
    "math/big"
)

func main() {
    f := big.NewInt(1)
    for i := int64(2); i <= 50; i++ {
        f.Mul(f, big.NewInt(i))
    }
    fmt.Println(f)
    fmt.Println(len(f.String()), "digits")
    var g big.Int
    fmt.Println(g.MulRange(1, 50).Cmp(f) == 0) // a built-in shortcut
}

Output:

30414093201713378043612608166064768844377641568960512000000000000
65 digits
true

50! has 65 digits. MulRange(a, b) multiplies all integers from a to b.

Quick quiz

1. What does this print? (From the video.)

s := []string{"9", "10", "100"}
sort.Strings(s)
n, err := strconv.Atoi(s[0])
fmt.Println(s, n, err)

A. [10 100 9] 10 <nil> · B. [9 10 100] 9 <nil> · C. [10 100 9] 9 <nil> · D. compile error

Answer

A. Strings sort character by character, so "10" and "100" come before "9". s[0] is "10", parsed to 10 with a nil error.

2. Which package should generate a password-reset token?

Answer

crypto/rand (for example crypto/rand.Text()), never math/rand.

3. Why does Go's regexp reject (?=...)?

Answer

It uses RE2 syntax, which leaves out features that need backtracking, so matching is guaranteed to run in linear time.

4. What does strconv.FormatInt(10, 2) return?

Answer

"1010", 10 in binary.

Interview questions

  1. How do you convert a string to an int in Go, and why isn't int(s) allowed? strconv.Atoi / ParseInt; parsing can fail, so it returns an error. Conversions only work between compatible types.
  2. What is the difference between sort.Slice and sort.SliceStable? Stable keeps equal elements in their original order.
  3. How would you sort structs by two keys? slices.SortFunc with cmp.Compare on the first key, then the second when the first is equal.
  4. Why shouldn't you store money in float64? Binary floats can't represent most decimal fractions exactly (0.1+0.2); use integer minor units or math/big.
  5. math/rand vs crypto/rand? Fast and predictable vs operating-system randomness for secrets.
  6. What is special about Go's regexp engine? RE2: linear-time matching, no backtracking, so no catastrophic slowdowns; no lookaround or backreferences.
  7. Why html/template instead of text/template for web pages? Contextual auto-escaping prevents XSS.
  8. How do you build a priority queue in Go? Implement heap.Interface (Len, Less, Swap, Push, Pop) and use heap.Init/Push/Pop; O(log n) per operation.
  9. When would you use container/list? Rarely: when you need O(1) insertion/removal in the middle with element handles (e.g. an LRU cache); slices are usually faster.

Glossary

Term Meaning Example
Standard library the packages that ship with Go strconv, sort, regexp
Conversion changing a value to a compatible type float64(3)
Parsing reading structured data out of text; can fail strconv.Atoi("12")
Formatting turning a value into text strconv.Itoa(12)
strconv "string conversions" package strconv.ParseFloat
Atoi / Itoa ASCII to integer / integer to ASCII "12" ↔ 12
ParseInt, ParseFloat, ParseBool parse text into numbers or bools ParseInt("ff", 16, 64)
FormatInt, FormatFloat numbers to text in a base / with digits FormatInt(255, 2)
Quote add quotes and escapes strconv.Quote("hi\n")
Base number system 2, 10, 16
Bit size integer size a result must fit in 8 → int8
ErrSyntax, ErrRange strconv's two error kinds invalid syntax / out of range
Rune conversion string(rune(n)) gives the character with code n "A"
Lexicographic order dictionary order, character by character "1200" < "45"
Less function func(i, j int) bool: does i come first? sort.Slice
sort.Slice sort a slice with a less function sort.Slice(xs, less)
Stable sort equal items keep their order slices.SortStableFunc
sort.Interface Len, Less, Swap sort.Sort(x)
sort.Reverse flip the order of a sort.Interface sort.Sort(sort.Reverse(x))
slices.SortFunc generic sort with a compare function slices.SortFunc(xs, cmpFn)
Compare function returns negative, 0 or positive cmp.Compare(a, b)
cmp.Compare compares two ordered values cmp.Compare(3, 5) = −1
Binary search search sorted data by halving slices.BinarySearchFunc
math float maths helpers and constants math.Sqrt(144)
math.MaxInt64 the largest int64 9223372036854775807
NaN / Inf not-a-number / infinity floats math.NaN()
Floating-point error tiny rounding errors of binary floats 0.30000000000000004
Paise 1/100 of a rupee; money as an int 250 rupees = 25000 paise
Overflow a result too big for its type; Go wraps around 25! in int64
Factorial product 1 × 2 × … × n 5! = 120
math/big arbitrary-size numbers big.Int, big.Rat, big.Float
big.Int an integer of any size big.NewInt(1)
big.Rat an exact fraction big.NewRat(1, 10)
Receiver (big) the value that receives the result f.Mul(f, x)
Pseudo-random numbers from a formula that look random math/rand/v2
Seed the starting number of a generator rand.NewPCG(2026, 11)
PCG a pseudo-random generator algorithm rand.NewPCG
math/rand/v2 fast pseudo-random numbers (Go 1.22) rand.IntN(100)
crypto/rand secure randomness from the operating system crand.Int, crand.Text()
Cryptographically secure impossible to predict in practice OTPs, tokens
OTP one-time password "366339"
Token a secret random string crand.Text()
Import alias a local name for an imported package crand "crypto/rand"
Regular expression (regex) a pattern describing the shape of text ^[6-9][0-9]{9}$
regexp.MustCompile compile a pattern, panic if invalid package variables
regexp.Compile compile a pattern, return an error user-given patterns
Capture group (...): a part of the match you want back PIN (\d{6})
Raw string literal backquoted string, no escapes `\d`
RE2 the regex syntax and engine Go uses no lookahead
Backtracking trying paths and going back; can be exponential Perl/PCRE engines
Linear time work grows in proportion to input size Go's regexp
Lookahead (?=...): a check that consumes nothing; not in RE2 a(?=b)
Template text with blanks (actions) filled from data "Dear {{.Name}}"
Action {{ ... }} in a template {{range .Items}}
Dot (.) the current data in a template {{.}}
text/template templates for any text receipts, emails
html/template templates for HTML, with auto-escaping web pages
Escaping turning special characters into safe text < → &lt;
XSS cross-site scripting: injected script runs in visitors' browsers <script> in a review
template.Must panic if a template fails to parse template.Must(t.Parse(s))
Priority queue always hands out the highest priority first emergency desk
Heap tree in a slice; best item at index 0 container/heap
Max-heap / min-heap largest / smallest on top Less with > / <
log n steps that grow very slowly with n 80,000 → ~17
heap.Init/Push/Pop build and use a heap heap.Pop(h)
Linked list elements linked to their neighbours container/list
Doubly linked list each element links to both neighbours l.PushFront
Ring a circular list container/ring
UTF-8 encoding where a character is 1–4 bytes "☕" is 3 bytes
Rune a Unicode character (int32) 'é'
utf8.RuneCountInString number of characters 6 for "Café ☕"
utf8.ValidString is this valid UTF-8? false for "\xff"

Summary

  • Text from outside is parsed with strconv (Atoi, ParseInt, ParseFloat); always check the error. Itoa/Format* go back.
  • Strings sort like a dictionary: parse, then sort. Use slices.SortFunc + cmp.Compare (stable: SortStableFunc); sort.Slice and sort.Interface in older code.
  • Floats aren't exact: money in integer paise; math/big for huge or exact numbers, at a speed cost.
  • math/rand/v2 for games; crypto/rand for anything secret.
  • regexp describes shapes of text; Go's RE2 engine always runs in linear time and has no lookahead.
  • Templates separate layout from data; html/template escapes HTML and prevents XSS.
  • container/heap is a priority queue (log n per operation); list and ring exist but slices usually win; unicode/utf8 counts and checks characters.

Next episode: Logging with log and log/slog: the log package, log.Fatal vs log.Panic, structured logging, TextHandler, JSONHandler, levels, attributes, LogValuer and custom handlers.