Golang: Cast is a safe and easy to use type conversion tool

safe and easy casting from one type to another in Go

The installation

package main
import (
    "fmt"
    "github.com/spf13/cast"
)
func main() {
    // 不处理错误
    i := cast.ToInt("8")
    fmt.Printf("%T: %v", i, i)
    // int: 8
    // 处理错误
    val, err := cast.ToIntE("8")
    if err == nil {
        fmt.Printf("%T: %v", val, val)
        // int: 8
    } else {
        fmt.Println(err)
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish