Go Cast Library: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Go Cast Library: The Complete Guide to Type Conversion

Go's strict static typing is both a strength and a challenge. On one hand, the compiler catches many errors at build time; on the other, developers must write verbose code for type conversion, especially when working with external data sources (JSON, YAML, databases, HTTP requests). The cast library by Spf13 (author of Cobra and Viper) solves this problem elegantly and concisely.

cast provides a set of functions for safely and conveniently converting interfaces (interface{}) to specific Go types. Instead of writing cumbersome type assertion constructs with error checks, you call a single function that returns a default value or an error if conversion is impossible. This is especially useful when working with configurations, parsing API responses, and any scenario where the data type is only known at runtime.

The library doesn't use reflection on every call (though some functions rely on it for complex conversions) and is designed to be as performant as possible for typical cases. It's part of the Viper ecosystem but can be used as a standalone utility. If you write Go and need to convert strings to numbers, interfaces to slices, or maps to structs, cast will become your indispensable tool.

Installation

Install the library using the standard go get tool. Run the following command in your terminal inside your Go module:

go get github.com/spf13/cast

After running the command, the library will be added to your go.mod file and ready to use. Make sure you have Go version 1.16 or higher installed (1.18+ is recommended for generics support, though cast doesn't use them).

Quick Start

Let's look at a minimal working example that demonstrates the library's core features: converting a string to an integer and an interface to a string.

package main

import (
    "fmt"
    "github.com/spf13/cast"
)

func main() {
    // Convert a string to int
    num, err := cast.ToIntE("42")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Printf("Number: %d (type: %T)\n", num, num)

    // Convert interface{} to string
    var val interface{} = "hello world"
    str := cast.ToString(val)
    fmt.Printf("String: %s (type: %T)\n", str, str)

    // Convert with fallback (no error)
    safeNum := cast.ToInt("not a number") // returns 0
    fmt.Printf("Safe number: %d\n", safeNum)
}

As you can see, the code is clean and readable. Functions with the E suffix return an error; those without it return a zero value on failure.

Key Methods and Functions

The cast library offers a wide range of functions for working with various data types. Below are 8+ key functions with descriptions and examples.

1. ToString

Signature: func ToString(i interface{}) string

What it does: Converts the given value to a string. Supports numeric types, boolean values, byte slices, strings, and interfaces.

package main

import (
    "fmt"
    "github.com/spf13/cast"
)

func main() {
    fmt.Println(cast.ToString(123))          // "123"
    fmt.Println(cast.ToString(45.67))        // "45.67"
    fmt.Println(cast.ToString(true))         // "true"
    fmt.Println(cast.ToString([]byte("go"))) // "go"
    fmt.Println(cast.ToString(nil))          // ""
}

2. ToInt

Signature: func ToInt(i interface{}) int

What it does: Converts a value to int. Works with strings

Recommendations