Skip to content
/ cvt Public

Easy and safe convert any value to another type in Go. (Go 数据类型安全转换)

License

Notifications You must be signed in to change notification settings

shockerli/cvt

Repository files navigation

cvt

PkgGoDev Go Report Card Build Status GitHub top language codecov GitHub

Simple, safe conversion of any type, including indirect/custom types.

Inspired by cast

Install

go get -u github.com/shockerli/cvt

Usage

中文说明

with error

Method __E(): expect handle error, while unable to convert

cvt.IntE("12")          // 12, nil
cvt.Float64E("12.34")   // 12.34, nil
cvt.StringE(12.34)      // "12.34", nil
cvt.BoolE("false")      // false, nil

custom type and pointers

dereferencing pointer and reach the base type

type Name string

var name Name = "jioby"

cvt.StringE(name)       // jioby, nil
cvt.StringE(&name)      // jioby, nil

ignore error

Method __(): ignore error, while convert failed, will return the zero value of type

cvt.Int("12")           // 12(success)
cvt.Int(struct{}{})     // 0(failed)

with default

return the default value, while convert failed

cvt.Int(struct{}{}, 12)     // 12
cvt.Float("hello", 12.34)   // 12.34

more

1000+ unit test cases, for more examples, see *_test.go

API

bool

  • Bool
  • BoolE

int

  • Int
  • IntE
  • Int8
  • Int8E
  • Int16
  • Int16E
  • Int32
  • Int32E
  • Int64
  • Int64E
  • Uint
  • UintE
  • Uint8
  • Uint8E
  • Uint16
  • Uint16E
  • Uint32
  • Uint32E
  • Uint64
  • Uint64E

string

  • String
  • StringE

float

  • Float32
  • Float32E
  • Float64
  • Float64E

time

  • Time
  • TimeE

slice

  • ColumnsE: the values from a single column in the input array/slice/map of struct/map, []interface{}
  • FieldE: the field value from map/struct, interface{}
  • KeysE: the keys of map, []interface{}
  • Slice
  • SliceE: convert an interface to a []interface{} type
  • SliceIntE: convert an interface to a []int type
  • SliceInt64E: convert an interface to a []int64 type
  • SliceFloat64E: convert an interface to a []float64 type
  • SliceStringE: convert an interface to a []string type

License

This project is under the terms of the MIT license.