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

cvt

PkgGoDev Go Report Card Build Status codecov GitHub Mentioned in Awesome Go

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

Install

go get -u github.com/shockerli/cvt

Usage

English | 中文

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 original 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
cvt.Bool(0)                 // false
cvt.Bool(nil)               // false
cvt.Bool("0")               // false
cvt.Bool("false")           // false
cvt.Bool([]int{})           // false

cvt.Bool(true)              // true
cvt.Bool("true")            // true
cvt.Bool([]int{1, 2})       // true
cvt.Bool([]byte("true"))    // true
  • BoolE
cvt.BoolE(0)                // false,nil
cvt.BoolE(nil)              // false,nil
cvt.BoolE("0")              // false,nil
cvt.BoolE("false")          // false,nil
cvt.BoolE([]int{})          // false,nil

cvt.BoolE(true)             // true,nil
cvt.BoolE("true")           // true,nil
cvt.BoolE([]int{1, 2})      // true,nil
cvt.BoolE([]byte("true"))   // true,nil

more case see bool_test.go

int

  • Int
  • IntE
  • Int8
  • Int8E
  • Int16
  • Int16E
  • Int32
  • Int32E
  • Int64
  • Int64E
  • Uint
  • UintE
  • Uint8
  • Uint8E
  • Uint16
  • Uint16E
  • Uint32
  • Uint32E
  • Uint64
  • Uint64E
cvt.Int(int8(8))            // 8
cvt.Int(int32(8))           // 8
cvt.Int("-8.01")            // -8
cvt.Int([]byte("8.00"))     // 8
cvt.Int(nil)                // 0
cvt.IntE("8a")              // 0,err
cvt.IntE([]int{})           // 0,err

// alias type
type OrderType uint8
cvt.Int(OrderType(3))       // 3

var po OrderType = 3
cvt.Int(&po)                // 3

more case see int_test.go

string

  • String
  • StringE
")) // "" cvt.String(json.Number("12.34")) // "12.34" // custom type type TestMarshalJSON struct{} func (TestMarshalJSON) MarshalJSON() ([]byte, error) { return []byte("custom marshal"), nil } cvt.String(TestMarshalJSON{}) // "custom marshal" cvt.String(&TestMarshalJSON{}) // "custom marshal"">
cvt.String(uint(8))             // "8"
cvt.String(float32(8.31))       // "8.31"
cvt.String(true)                // "true"
cvt.String([]byte("-8.01"))     // "-8.01"
cvt.String(nil)                 // ""

cvt.String(errors.New("error info"))            // "error info"
cvt.String(time.Friday)                         // "Friday"
cvt.String(big.NewInt(123))                     // "123"
cvt.String(template.URL("https://host.foo"))    // "https://host.foo"
cvt.String(template.HTML(""))      // ""
cvt.String(json.Number("12.34"))                // "12.34"

// custom type
type TestMarshalJSON struct{}

func (TestMarshalJSON) MarshalJSON() ([]byte, error) {
    return []byte("custom marshal"), nil
}
cvt.String(TestMarshalJSON{})   // "custom marshal"
cvt.String(&TestMarshalJSON{})  // "custom marshal"

more case see string_test.go

float

  • Float32
  • Float32E
  • Float64
  • Float64E
cvt.Float64(int32(8))       // 8
cvt.Float64(float32(8.31))  // 8.31
cvt.Float64("-8")           // 8
cvt.Float64("-8.01")        // 8.01
cvt.Float64(nil)            // 0
cvt.Float64(true)           // 1
cvt.Float64(false)          // 0

type AliasTypeInt int
type PointerTypeInt *AliasTypeInt
cvt.Float64(AliasTypeInt(8))            // 8
cvt.Float64((*AliasTypeInt)(nil))       // 0
cvt.FLoat64((*PointerTypeInt)(nil))     // 0

more case see float_test.go

time

  • Time
  • TimeE
cvt.Time("2009-11-10 23:00:00 +0000 UTC")
cvt.Time("2018-10-21T23:21:29+0200")
cvt.Time("10 Nov 09 23:00 UTC")
cvt.Time("2009-11-10T23:00:00Z")
cvt.Time("11:00PM")
cvt.Time("2006-01-02")
cvt.Time("2016-03-06 15:28:01")
cvt.Time(1482597504)
cvt.Time(time.Date(2009, 2, 13, 23, 31, 30, 0, time.Local))

more case see time_test.go

slice

  • ColumnsE: the values from a single column in the input array/slice/map of struct/map, []interface{}
// []interface{}{"D1", "D2", nil}
cvt.ColumnsE([]map[string]interface{}{
	  {"1": 111, "DDD": "D1"},
	  {"2": 222, "DDD": "D2"},
	  {"DDD": nil},
}, "DDD")

// test type
type TestStructD struct {
    D1 int
}
type TestStructE struct {
    D1 int
    DD *TestStructD
}

// []interface{}{11, 22}
cvt.ColumnsE(map[int]TestStructD{1: {11}, 2: {22}}, "D1")

// []interface{}{1, 2}
cvt.ColumnsE([]TestStructE{{D1: 1}, {D1: 2}}, "D1")
  • FieldE: the field value from map/struct, interface{}
// map
cvt.FieldE(map[int]interface{}{123: "112233"}, "123") // "112233"
cvt.FieldE(map[string]interface{}{"123": "112233"}, "123") // "112233"

// struct
cvt.FieldE(struct{
	  A string
	  B int
}{"Hello", 18}, "A") // "Hello"
cvt.FieldE(struct{
	  A string
	  B int
}{"Hello", 18}, "B") // 18
  • KeysE: the keys of map, or fields of struct, []interface{}
cvt.KeysE()
// key of map
cvt.KeysE(map[float64]float64{0.1: -0.1, -1.2: 1.2}) // []interface{}{-1.2, 0.1}
cvt.KeysE(map[string]interface{}{"A": 1, "2": 2}) // []interface{}{"2", "A"}
cvt.KeysE(map[int]map[string]interface{}{1: {"1": 111, "DDD": 12.3}, -2: {"2": 222, "DDD": "321"}, 3: {"DDD": nil}}) // []interface{}{-2, 1, 3}

// field name of struct
cvt.KeysE(struct{
	  A string
	  B int
	  C float
}{}) // []interface{}{"A", "B", "C"}

type TestStructB {
	  B int
}
cvt.KeysE(struct{
	  A string
    TestStructB
	  C float
}{}) // []interface{}{"A", "B", "C"}
  • 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
cvt.SliceE("hello")                             // []interface{}{'h', 'e', 'l', 'l', 'o'}
cvt.SliceE([]byte("hey"))                       // []interface{}{byte('h'), byte('e'), byte('y')}
cvt.SliceE([]int{1, 2, 3})                      // []interface{}{1, 2, 3}
cvt.SliceE([]string{"a", "b", "c"})             // []interface{}{"a", "b", "c"}
cvt.SliceE(map[int]string{1: "111", 2: "222"})  // []interface{}{"111", "222"}

// struct values
type TestStruct struct {
    A int
    B string
}
cvt.SliceE(TestStruct{18,"jhon"}) // []interface{}{18, "jhon"}

// SliceIntE
cvt.SliceIntE([]string{"1", "2", "3"})              // []int{1, 2, 3}
cvt.SliceIntE(map[int]string{2: "222", 1: "111"})   // []int{111, 222}

// SliceStringE
cvt.SliceStringE([]float64{1.1, 2.2, 3.0})              // []string{"1.1", "2.2", "3"}
cvt.SliceStringE(map[int]string{2: "222", 1: "11.1"})   // []string{"11.1", "222"}

more case see slice_test.go

map

  • StringMapE
// JSON
// expect: map[string]interface{}{"name": "cvt", "age": 3.21}
cvt.StringMapE(`{"name":"cvt","age":3.21}`)

// Map
// expect: map[string]interface{}{"111": "cvt", "222": 3.21}
cvt.StringMapE(map[interface{}]interface{}{111: "cvt", "222": 3.21})

// Struct
// expect: map[string]interface{}{"Name": "cvt", "Age": 3}
cvt.StringMapE(struct {
    Name string
    Age  int
}{"cvt", 3})

more case see map_test.go

License

This project is under the terms of the MIT license.

Thanks

JetBrains Logo (Main) logo

Owner
Jioby
follow my heart
Jioby
Similar Resources

go.fifo provides a simple fifo thread-safe queue for the Go programming language

go.fifo Description go.fifo provides a simple FIFO thread-safe queue. *fifo.Queue supports pushing an item at the end with Add(), and popping an item

Aug 29, 2022

A simple and efficient thread-safe sharded hashmap for Go

shardmap A simple and efficient thread-safe sharded hashmap for Go. This is an alternative to the standard Go map and sync.Map, and is optimized for w

Dec 17, 2022

A simple set type for the Go language. Trusted by Docker, 1Password, Ethereum and Hashicorp.

golang-set The missing set collection for the Go language. Until Go has sets built-in...use this. Coming from Python one of the things I miss is the s

Jan 8, 2023

Nullable Go types that can be marshalled/unmarshalled to/from JSON.

Nullable Go types Description This package provides nullable Go types for bool, float64, int64, int32, string and time.Time replacing sql.NullString,

Dec 12, 2022

succinct provides several static succinct data types

succinct provides several static succinct data types Succinct Set Synopsis Performance Implementation License Succinct Set

Jan 5, 2023

Go strcut based enum, support all types.

go-ultra-enum go-ultra-enum is an enum generator for Go. It is inspired by the powerful enum types found in Java. go-ultra-enum has the following capa

Dec 21, 2021

Package iter provides generic, lazy iterators, functions for producing them from primitive types, as well as functions and methods for transforming and consuming them.

iter Package iter provides generic, lazy iterators, functions for producing them from primitive types, as well as functions and methods for transformi

Dec 16, 2022

Package ring provides a high performance and thread safe Go implementation of a bloom filter.

ring - high performance bloom filter Package ring provides a high performance and thread safe Go implementation of a bloom filter. Usage Please see th

Nov 20, 2022

A thread safe map which has expiring key-value pairs

~ timedmap ~ A map which has expiring key-value pairs. go get github.com/zekroTJA/timedmap Intro This package allows to set values to a map which will

Dec 29, 2022
Comments
  • 关于转换之后的值跟实际的值不一样是否应该返回错误呢?

    关于转换之后的值跟实际的值不一样是否应该返回错误呢?

    请问这段代码运行结果是否应该返回error 因为实际他的值已经不是原来的值了

    fmt.Println(cvt.IntE("12.1")) // 12 <nil> 
    fmt.Println(strconv.ParseInt("12.1", 10, 64)) // 0 strconv.ParseInt: parsing "12.1": invalid syntax
    
  • cvt.Int64转换出错

    cvt.Int64转换出错

    package main
    
    import (
    	"fmt"
    
    	"github.com/shockerli/cvt"
    )
    
    func main() {
    	fmt.Print("7138826985640367621", "\n")
    	fmt.Print(cvt.Int64("7138826985640367621"), "\n")
    }
    
    

    输出

    7138826985640367621
    7138826985640368128
    
  • `StringMapE` support JSON for []byte

    `StringMapE` support JSON for []byte

    • StringMapE support JSON for []byte
    cvt.StringMapE([]byte(`{"name":"cvt","build":true}`))
    cvt.StringMapE(AliasTypeString(`{"name":"cvt","build":true}`))
    cvt.StringMapE(AliasTypeBytes(`{"name":"cvt","build":true}`))
    
    • add 4 unit test case for int*
    cvt.IntE("00100") // 100
    cvt.IntE("-00100") // -100
    cvt.IntE("00100.00") // 100
    cvt.IntE("-00100.01") // -100
    
  • Add func `StringMapE`

    Add func `StringMapE`

    func

    func StringMapE(val interface{}) (m map[string]interface{}, err error)
    

    feature

    • Support JSON string of map
    // input
    `{"name":"cvt","age":3.21}`
    
    // expect
    map[string]interface{}{"name": "cvt", "age": 3.21} 
    
    • Support any map type
    // input
    map[interface{}]interface{}{111: "cvt", "222": 3.21}
    
    // expect
    map[string]interface{}{"111": "cvt", "222": 3.21}
    
    • Support any struct type
    // input
    struct {
        Name string
        Age  int
    }{"cvt", 3}
    
    // expect
    map[string]interface{}{"Name": "cvt", "Age": 3}
    
Go concurrent-safe, goroutine-safe, thread-safe queue
Go concurrent-safe, goroutine-safe, thread-safe queue

goconcurrentqueue - Concurrent safe queues The package goconcurrentqueue offers a public interface Queue with methods for a queue. It comes with multi

Dec 31, 2022
Generic types that are missing from Go, including sets, trees, sorted lists, etc.

go-typ Generic types that are missing from Go, including sets, trees, sorted lists, etc. All code is implemented with 0 dependencies and in pure Go co

Dec 4, 2022
Custom generic HTTP handler providing automatic JSON decoding/encoding of HTTP request/response to your concrete types

gap Custom generic HTTP handler providing automatic JSON decoding/encoding of HTTP request/response to your concrete types. gap.Wrap allows to use the

Aug 28, 2022
Type-safe, zero-allocation sets for Go

Set Package set is a type-safe, zero-allocation port of the excellent package fatih/set. It contains sets for most of the basic types and you can gene

Jan 5, 2023
Zero allocation Nullable structures in one library with handy conversion functions, marshallers and unmarshallers

nan - No Allocations Nevermore Package nan - Zero allocation Nullable structures in one library with handy conversion functions, marshallers and unmar

Dec 20, 2022
Provides conversion from athena outputs to strongly-typed data models.
Provides conversion from athena outputs to strongly-typed data models.

Provides conversion from athena outputs to strongly defined data models. Getting started Given the following data struct you define: type MyModel stru

Feb 7, 2022
💯 Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

Package validator implements value validations for structs and individual fields based on tags.

Nov 9, 2022
Convert arbitrary formats to Go Struct (including json, toml, yaml, etc.)

go2struct Convert arbitrary formats to Go Struct (including json, toml, yaml, etc.) Installation Run the following command under your project: go get

Nov 15, 2022
Clone a directory (including permissions) into S3 for File Gateway usage

s3-tree-clone Clone a filesystem tree to S3 (including metadata), skipping over files that are already synced, in a manner compatible with AWS File Ga

Dec 2, 2021
Juniper is an extension to the Go standard library using generics, including containers, iterators, and streams.

Juniper Juniper is a library of extensions to the Go standard library using generics, including containers, iterators, and streams. container/tree con

Dec 25, 2022