0
点赞
收藏
分享

微信扫一扫

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

safe and easy casting from one type to another in Go

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

文档

  • https://pkg.go.dev/github.com/spf13/cast
  • https://github.com/spf13/cast

安装

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工具箱」一个简单、易用、安全的类型转换工具

举报

相关推荐

0 条评论