Skip to content

spf13/cast ​

Before You Start

  • Applies to: Go 1.21+ (examples verified with Go 1.22) · Prerequisites: Base: Data Types · Read time: about 8 min

Repository: spf13/cast: safe and easy casting from one type to another in Go (github.com)

Documentation: spf13/cast: safe and easy casting from one type to another in Go (github.com)

Introduction ​

cast is a simple type conversion library for fast conversion from one type to another, saving you from many tedious operations.

Installation ​

go get https://github.com/spf13/cast

Examples ​

String

go
cast.ToString("mayonegg")         // "mayonegg"
cast.ToString(8)                  // "8"
cast.ToString(8.31)               // "8.31"
cast.ToString([]byte("one time")) // "one time"
cast.ToString(nil)                // ""

var foo interface{} = "one more time"
cast.ToString(foo)                // "one more time"

Integer

go
cast.ToInt(8)                  // 8
cast.ToInt(8.31)               // 8
cast.ToInt("8")                // 8
cast.ToInt(true)               // 1
cast.ToInt(false)              // 0

var eight interface{} = 8
cast.ToInt(eight)              // 8
cast.ToInt(nil)                // 0

Complete Example ​

The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.

go
package main

import (
	"fmt"
	"strconv"
)

func toInt(v any) int {
	switch x := v.(type) {
	case int:
		return x
	case string:
		n, _ := strconv.Atoi(x)
		return n
	case float64:
		return int(x)
	default:
		return 0
	}
}

func main() {
	fmt.Println(toInt("42"), toInt(7), toInt(3.9), toInt(nil))
}

Expected output:

text
42 7 3 0

Common Pitfalls ​

  • Failed conversions return zero silently. cast.ToInt("abc") is 0; validate input when zero is a valid value.
  • Floats truncate. cast.ToInt(3.9) is 3; use rounding explicitly if that is what you mean.
  • nil maps to the zero value. Do not use the result to distinguish "missing" from zero.
  • Booleans become 1/0. Convenient, but easy to confuse in mixed data.
  • Time parsing assumes layouts. cast.ToTime guesses; pass a layout for anything business-critical.

Change Log ​

  • 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log. Closed a code block that was left unterminated.

Golang by www.golangdev.cn · Adapted in part from Golang 中文学习文档 (MIT, © 寒江蓑笠翁)