SoFunction
Updated on 2025-03-05

Detailed explanation of the use of golang type conversion component Cast

Open source address

/spf13/cast

What is Cast?

Cast is a library that converts between different go types in a consistent and simple way.

Cast provides simple functions that can easily convert numbers to strings, interfaces to bool types, and more. Cast intelligently performs this when an obvious transformation is possible. It won't try to guess what you mean, for example, you can only convert a string to an int's string representation, such as "8". Cast was developed for Hugo, a website engine that uses YAML, TOML, or JSON as metadata.

Why use Cast?

When processing dynamic data in Go, it is often necessary to convert data from one type to another. Casting is not just about using type assertions (although it uses type assertions where possible), it provides a very straightforward and convenient library.

If you are using an interface to handle things like dynamic content, you will need an easy way to convert the interface to a given type. This is for you the library.

If you get data from YAML, TOML, or JSON, or other formats that lack the full type, then Cast is the library for you.

How to use

Casting provides some To______ methods. These methods will always return the desired type. If the provided input cannot be converted to this type, a 0 or nil value of that type is returned.

Cast also provides the same method as To_____E. These methods return the same result as the To_____ method, plus an additional error telling you whether the conversion is successful. Using these methods, you can tell the difference when the input matches a zero value and when the conversion fails to return a zero value.

Case

The following example is only one example of the existing example. Please see the complete code set.

Example ‘ToString':

("mayonegg")   // "mayonegg"
(8)     // "8"
(8.31)    // "8.31"
([]byte("one time")) // "one time"
(nil)    // ""

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

Example ‘ToInt':

(8)     // 8
(8.31)    // 8
("8")    // 8
(true)    // 1
(false)    // 0

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

main function

package main

import (
	"fmt"
	"reflect"

	"/spf13/cast"
)

func main() {
	var foo interface{} = "one more time"
	box := (foo)
	(box)
	box = ("3.12021")
	(box)

	cvIntBox := (8)
	(cvIntBox, (cvIntBox))
	cvFloatBox := cast.ToFloat32(8.31)
	(cvFloatBox, (cvFloatBox))
	cvBoolBox := (true)
	(cvBoolBox, (cvBoolBox))
}

Output

one more time
3.12021
8 int
8.31 float32
true bool

The above is the detailed explanation of the use of golang type conversion component Cast. For more information about golang type conversion component Cast, please follow my other related articles!