Golang:cast安全且易用的类型转换工具

safe and easy casting from one type to another in Go

译文:安全且容易从一种类型转换到另一种类型

文档

安装

go get github.com/spf13/cast

示例

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)
    }

}

参考
「Go工具箱」一个简单、易用、安全的类型转换工具

猜你喜欢

转载自blog.csdn.net/mouday/article/details/126967098
今日推荐