0Pricing
Go Academy · Lesson

strconv, math and sort

Type conversion, math utilities, and sorting

strconv, math and sort is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

strconv: String Conversions

The strconv package converts between strings and basic types:

package main
import ("fmt"; "strconv")

func main() {
    // String to int
    n, err := strconv.Atoi("42")
    fmt.Println(n, err)           // 42 <nil>

    // Int to string
    s := strconv.Itoa(123)
    fmt.Println(s)                // "123"

    // String to float64
    f, _ := strconv.ParseFloat("3.14", 64)
    fmt.Println(f)                // 3.14

    // Float64 to string
    fs := strconv.FormatFloat(f, 'f', 2, 64)
    fmt.Println(fs)               // "3.14"
}

strconv.ParseInt and ParseBool

Parse integers with base and bool values:

package main
import ("fmt"; "strconv")

func main() {
    // Parse int with base
    n, _ := strconv.ParseInt("FF", 16, 64)   // hex
    fmt.Println(n)  // 255

    n2, _ := strconv.ParseInt("11111111", 2, 64) // binary
    fmt.Println(n2) // 255

    // Bool parsing
    b1, _ := strconv.ParseBool("true")
    b2, _ := strconv.ParseBool("1")
    b3, _ := strconv.ParseBool("T")
    fmt.Println(b1, b2, b3) // true true true
}

strconv Error Handling

Always handle strconv errors — invalid input returns an error wrapped in *strconv.NumError:

package main
import ("fmt"; "strconv")

func safeAtoi(s string) (int, error) {
    n, err := strconv.Atoi(s)
    if err != nil {
        return 0, fmt.Errorf("invalid integer %q: %w", s, err)
    }
    return n, nil
}

func main() {
    n, err := safeAtoi("abc")
    fmt.Println(n, err)
    // 0 invalid integer "abc": strconv.Atoi: ...
}

math Package Essentials

The math package provides mathematical constants and functions:

package main
import ("fmt"; "math")

func main() {
    fmt.Println(math.Pi)           // 3.141592653589793
    fmt.Println(math.E)            // 2.718281828459045
    fmt.Println(math.Sqrt(16))     // 4
    fmt.Println(math.Pow(2, 10))   // 1024
    fmt.Println(math.Abs(-5.5))    // 5.5
    fmt.Println(math.Floor(3.7))   // 3
    fmt.Println(math.Ceil(3.2))    // 4
    fmt.Println(math.Round(3.5))   // 4
    fmt.Println(math.Log(math.E))  // 1
    fmt.Println(math.Log2(8))      // 3
}

math.MaxInt and Float Limits

Use math constants for integer and float limits:

package main
import ("fmt"; "math")

func main() {
    fmt.Println(math.MaxInt)      // max int (platform-dependent)
    fmt.Println(math.MinInt)      // min int
    fmt.Println(math.MaxInt32)    // 2147483647
    fmt.Println(math.MaxFloat64)  // 1.7976931348623157e+308
    fmt.Println(math.SmallestNonzeroFloat64)
    fmt.Println(math.IsInf(math.Inf(1), 1)) // true
    fmt.Println(math.IsNaN(math.NaN()))     // true
}

math/rand — Random Numbers

Generate random numbers with math/rand (Go 1.20+ auto-seeded):

package main
import ("fmt"; "math/rand")

func main() {
    // Go 1.20+: automatically seeded
    fmt.Println(rand.Intn(100))     // random 0-99
    fmt.Println(rand.Float64())     // random [0.0, 1.0)

    // Shuffle a slice
    s := []int{1, 2, 3, 4, 5}
    rand.Shuffle(len(s), func(i, j int) {
        s[i], s[j] = s[j], s[i]
    })
    fmt.Println(s)
}

sort.Slice — Quick Custom Sorting

Sort any slice with a custom comparator using sort.Slice:

package main
import ("fmt"; "sort")

func main() {
    people := []struct{ Name string; Age int }{
        {"Alice", 30}, {"Bob", 25}, {"Carol", 35},
    }

    // Sort by age ascending
    sort.Slice(people, func(i, j int) bool {
        return people[i].Age < people[j].Age
    })
    fmt.Println(people)
    // [{Bob 25} {Alice 30} {Carol 35}]
}

sort.Strings, sort.Ints, sort.Float64s

Built-in sort functions for common slice types:

package main
import ("fmt"; "sort")

func main() {
    strs := []string{"banana", "apple", "cherry"}
    sort.Strings(strs)
    fmt.Println(strs)  // [apple banana cherry]

    nums := []int{5, 2, 8, 1, 9, 3}
    sort.Ints(nums)
    fmt.Println(nums)  // [1 2 3 5 8 9]

    // Check if already sorted:
    fmt.Println(sort.IntsAreSorted(nums)) // true
}

sort.Search — Binary Search

sort.Search performs a binary search over a sorted slice:

package main
import ("fmt"; "sort")

func main() {
    nums := []int{1, 3, 5, 7, 9, 11, 13}
    target := 7

    i := sort.Search(len(nums), func(i int) bool {
        return nums[i] >= target
    })

    if i < len(nums) && nums[i] == target {
        fmt.Printf("Found %d at index %d\n", target, i) // Found 7 at index 3
    }
}

slices Package (Go 1.21+)

Go 1.21 added the slices package with generic sort and search functions:

package main
import ("fmt"; "slices")

func main() {
    nums := []int{5, 2, 8, 1}
    slices.Sort(nums)                  // in-place sort
    fmt.Println(nums)                  // [1 2 5 8]

    strs := []string{"c", "a", "b"}
    slices.Sort(strs)
    fmt.Println(strs)                  // [a b c]

    idx, found := slices.BinarySearch(nums, 5)
    fmt.Println(idx, found)            // 2 true
}

Quick Check

Which function converts an integer to its string representation in Go?

Recap: strconv, math, sort

Summary:

  • strconv.Atoi/Itoa, ParseFloat/FormatFloat, ParseBool for conversions
  • math.Sqrt/Pow/Abs/Floor/Ceil/Round for mathematics
  • math.MaxInt/MaxFloat64 for type limits
  • sort.Slice for custom sort, sort.Strings/Ints for primitives
  • sort.Search for binary search
  • slices package (Go 1.21+) for generic alternatives

Frequently asked questions

Is the “strconv, math and sort” lesson free?

Yes — the full text of “strconv, math and sort” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “strconv, math and sort”?

Type conversion, math utilities, and sorting You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “strconv, math and sort” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. fmt and strings Packages
  2. strconv, math and sort
  3. time Package Essentials
  4. os and filepath Packages
← Back to Go Academy