types

package
v5.2.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2019 License: Apache-2.0 Imports: 6 Imported by: 4

Documentation

Overview

Package types supplies some assistant functions about type, such as the type validation and conversion, etc.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotSliceOrArray is returned when the value is not a slice.
	ErrNotSliceOrArray = fmt.Errorf("the value is not a slice or array")

	// ErrNotMap is returned when the value is not a map.
	ErrNotMap = fmt.Errorf("the value is not a map")

	// ErrNotString is returned when the type of the key is not string.
	ErrNotString = fmt.Errorf("the type of the key is not string")

	// ErrKindNotExist is returned when a certain kind does not exist.
	ErrKindNotExist = fmt.Errorf("no kind")
)

Functions

func Convert

func Convert(k Kind, v interface{}) (interface{}, error)

Convert calls the converter of the kind k to convert the value v.

If the converter of the kind k does not exists, it returns ErrKindNotExist.

func IsZero

func IsZero(v interface{}) bool

IsZero judges whether a value is ZERO.

For "", 0, 0.0, false, 0+0i, nil, and the slice, array or map that the length is 0, they are all ZERO. Others is not ZERO.

Example
// bool
fmt.Println("bool:", IsZero(true), IsZero(false))

// int, int8, int16, int32, int64, rune
fmt.Println("int:", IsZero(int(1)), IsZero(int(0)))

// uint, uint8, uint16, uint32, uint64, byte
fmt.Println("uint:", IsZero(uint(1)), IsZero(uint(0)))

// complex64, complex128
fmt.Println("complex:", IsZero(complex64(1.1+1.1i)),
	IsZero(complex64(0.0+0.0i)))

// chan, func, map, slice
var c chan string
var f func()
var m map[string]string
var s []string
fmt.Println("chan func map slice:", IsZero(c), IsZero(f), IsZero(m),
	IsZero(s))

// ptr
ii := 11
fmt.Println("ptr:", IsZero(&ii), IsZero((*int)(nil)))

// array
fmt.Println("array:", IsZero([3]int{1, 2, 3}), IsZero([0]int{}))

// string
fmt.Println("string:", IsZero("123"), IsZero(""))

// struct
type S struct{}
fmt.Println("struct:", IsZero(S{}))

// interface
fmt.Println("interface:", IsZero(interface{}(nil)))
Output:

bool: false true
int: false true
uint: false true
complex: false true
chan func map slice: true true true true
ptr: false true
array: false true
string: false true
struct: false
interface: true

func MustToBool

func MustToBool(v interface{}) bool

MustToBool is equal to ToBool, but panic if there is an error.

func MustToComplex128

func MustToComplex128(v interface{}) complex128

MustToComplex128 is equal to ToComplex128, but panic if there is an error.

func MustToFloat64

func MustToFloat64(v interface{}) float64

MustToFloat64 is equal to ToFloat64, but panic if there is an error.

func MustToInt

func MustToInt(v interface{}) int

MustToInt is equal to ToInt, but panic if there is an error.

func MustToInt16

func MustToInt16(v interface{}) int16

MustToInt16 is equal to ToInt16, but panic if there is an error.

func MustToInt32

func MustToInt32(v interface{}) int32

MustToInt32 is equal to ToInt32, but panic if there is an error.

func MustToInt64

func MustToInt64(v interface{}) int64

MustToInt64 is equal to ToInt64, but panic if there is an error.

func MustToInt8

func MustToInt8(v interface{}) int8

MustToInt8 is equal to ToInt8, but panic if there is an error.

func MustToMap

func MustToMap(v interface{}) map[string]interface{}

MustToMap is equal to ToMap, but panic if there is an error.

func MustToMapKeys

func MustToMapKeys(v interface{}) []string

MustToMapKeys is equal to ToMapKeys, but panic if there is an error.

func MustToMapValues

func MustToMapValues(v interface{}) []interface{}

MustToMapValues is equal to ToMapValues, but panic if there is an error.

func MustToSlice

func MustToSlice(v interface{}) []interface{}

MustToSlice is equal to ToSlice, but panic if there is an error.

func MustToString

func MustToString(v interface{}) string

MustToString is equal to ToString, but panic if there is an error.

func MustToTime

func MustToTime(v interface{}, layout ...string) time.Time

MustToTime is equal to ToTime, but panic if there is an error.

func MustToUint

func MustToUint(v interface{}) uint

MustToUint is equal to ToUint, but panic if there is an error.

func MustToUint16

func MustToUint16(v interface{}) uint16

MustToUint16 is equal to ToUint16, but panic if there is an error.

func MustToUint32

func MustToUint32(v interface{}) uint32

MustToUint32 is equal to ToUint32, but panic if there is an error.

func MustToUint64

func MustToUint64(v interface{}) uint64

MustToUint64 is equal to ToUint64, but panic if there is an error.

func MustToUint8

func MustToUint8(v interface{}) uint8

MustToUint8 is equal to ToUint8, but panic if there is an error.

func NameToType

func NameToType(name string) string

NameToType returns the type string by the name.

The name is the name used by VerifyType, such as string for string, strings for []string, or string2string for map[string]string.

Example
fmt.Println(NameToType("string"))
fmt.Println(NameToType("strings"))
fmt.Println(NameToType("string2string"))
Output:

string
[]string
map[string]string

func RegisterConverter

func RegisterConverter(k Kind, converter func(interface{}) (interface{}, error))

RegisterConverter registers a converter of the kind k.

By default it has registered the kinds as follow:

Bool
String
Float64
Int, Int32, Int64
Uint, Uint32, Uint64
Time, RFC3339Time

func RegisterVerifyFunc

func RegisterVerifyFunc(t string, f VerifyFunc) error

RegisterVerifyFunc registers a type verification function.

func ToBool

func ToBool(v interface{}) (bool, error)

ToBool does the best to convert any certain value to bool.

For the string, the true value is

"t", "T", "1", "on", "On", "ON", "true", "True", "TRUE", "yes", "Yes", "YES"

the false value is

"f", "F", "0", "off", "Off", "OFF", "false", "False", "FALSE", "no", "No", "NO", ""

For other types, if the value is ZERO of the type, it's false. Or it's true.

func ToComplex128

func ToComplex128(_v interface{}) (v complex128, err error)

ToComplex128 does the best to convert any certain value to complex128.

func ToFloat64

func ToFloat64(_v interface{}) (v float64, err error)

ToFloat64 does the best to convert any certain value to float64.

func ToInt

func ToInt(v interface{}) (int, error)

ToInt does the best to convert any certain value to int.

func ToInt16

func ToInt16(v interface{}) (int16, error)

ToInt16 does the best to convert any certain value to int16.

func ToInt32

func ToInt32(v interface{}) (int32, error)

ToInt32 does the best to convert any certain value to int32.

func ToInt64

func ToInt64(_v interface{}) (v int64, err error)

ToInt64 does the best to convert any certain value to int64.

func ToInt8

func ToInt8(v interface{}) (int8, error)

ToInt8 does the best to convert any certain value to int8.

func ToMap

func ToMap(v interface{}) (map[string]interface{}, error)

ToMap converts any map type that the key is string to map[string]interface{}.

Return nil and an error if v is not a map type or its key is not the string type.

If you ensure that v is a map, and its key is the string type, you can ignore the error.

For []interface{}, []string and []int, they have already been optimized.

func ToMapKeys

func ToMapKeys(v interface{}) ([]string, error)

ToMapKeys returns all the keys of a map.

If the value is not a map or the key is not string, it returns an error. But if the value is nil, it will return a empty slice, not an error instead.

If you ensure that v is a map, and its key is the string type, you can ignore the error.

For map[string]interface{}, map[string]string and map[string]int, they have already been optimized.

func ToMapValues

func ToMapValues(v interface{}) ([]interface{}, error)

ToMapValues returns all the values of a map.

If the value is not a map, it returns an error. But if the value is nil, it will return a empty slice, not an error instead.

If you ensure that v is a map, you can ignore the error.

For map[string]interface{}, map[string]string and map[string]int, they have already been optimized.

func ToSlice

func ToSlice(v interface{}) ([]interface{}, error)

ToSlice converts any slice type of []interface{}.

Return nil and an error if v is not a slice type.

For []interface{}, []string and []int, they have already been optimized.

func ToString

func ToString(_v interface{}) (v string, err error)

ToString does the best to convert any certain value to string.

For time.Time, it will use time.RFC3339Nano to format it.

func ToTime

func ToTime(v interface{}, layout ...string) (time.Time, error)

ToTime does the best to convert any certain value to time.Time.

Notice: the layout is time.RFC3339Nano by default.

func ToUint

func ToUint(v interface{}) (uint, error)

ToUint does the best to convert any certain value to uint.

func ToUint16

func ToUint16(v interface{}) (uint16, error)

ToUint16 does the best to convert any certain value to uint16.

func ToUint32

func ToUint32(v interface{}) (uint32, error)

ToUint32 does the best to convert any certain value to uint32.

func ToUint64

func ToUint64(_v interface{}) (v uint64, err error)

ToUint64 does the best to convert any certain value to uint64.

func ToUint8

func ToUint8(v interface{}) (uint8, error)

ToUint8 does the best to convert any certain value to uint8.

func VerifyMapValueType

func VerifyMapValueType(m interface{}, k, t string) (ok bool)

VerifyMapValueType verifies whether the type of the value of the key in the map is the given type.

Return false if m is not the map type or the map does not have the key.

Notice: the type of the key of the map type must be string, or return false.

Example
v1 := map[string]interface{}{
	"a": 11,
	"b": "22",
}
v2 := map[int]interface{}{
	1: "a",
	2: "b",
}

fmt.Println(VerifyMapValueType(v1, "a", "int"))
fmt.Println(VerifyMapValueType(v1, "b", "string"))
fmt.Println(VerifyMapValueType(v1, "b", "int"))
fmt.Println(VerifyMapValueType(v1, "c", "string"))
fmt.Println(VerifyMapValueType(v2, "1", "string"))
Output:

true
true
false
false
false

func VerifySliceValueType

func VerifySliceValueType(slice interface{}, i int, t string) (ok bool)

VerifySliceValueType verifies whether the type of the ith value of the slice is the given type.

Return false if the ith value of slice does not exist, that's, i>=len(slice). Return false if slice is not a slice or array type, too.

func VerifyType

func VerifyType(v interface{}, t string) bool

VerifyType verifies whether the type of v is t.

The supported types are below:

t(string)           Go Type / Function Call
-------------------------------------------
"zero"              IsZero(v)
"nil"               nil
"bool"              bool
"string"            string
"byte"              byte
"rune"              rune
"int"               int
"int8"              int8
"int16"             int16
"int32"             int32
"int64"             int64
"uint"              uint
"uint8"             uint8
"uint16"            uint16
"uint32"            uint32
"uint64"            uint64
"float32"           float32
"float64"           float64
"complex64"         complex64
"complex128"        complex128
"bools"             []bool
"strings"           []string
"bytes"             []byte
"runes"             []rune
"ints"              []int
"int8s"             []int8
"int16s"            []int16
"int32s"            []int32
"int64s"            []int64
"uints"             []uint
"uint8s"            []uint8
"uint16s"           []uint16
"uint32s"           []uint32
"uint64s"           []uint64
"float32s"          []float32
"float64s"          []float64
"complex64s"        []complex64
"complex128s"       []complex128
"string2string"     map[string]string,
"string2interface"  map[string]interface{}
"int642interface"   map[int64]interface{}
"int642string"      map[int64]string
"int2string"        map[int]string
"int2interface"     map[int]interface{}
"uint642interface"  map[uint64]interface{}
"uint642string"     map[uint64]string
"uint2string"       map[uint]string
"uint2interface"    map[uint]interface{}

Notice: You can add the new type verification by RegisterVerifyFunc it.

Example
fmt.Println(VerifyType(int64(1), "int64"))
fmt.Println(VerifyType(int64(1), "int32"))
fmt.Println(VerifyType(byte(1), "uint8"))
fmt.Println(VerifyType(byte(1), "int8"))
fmt.Println(VerifyType("123", "string"))
fmt.Println(VerifyType("123", "bytes"))

fmt.Println(VerifyType([]byte("123"), "bytes"))
fmt.Println(VerifyType([]byte("123"), "string"))
fmt.Println(VerifyType(map[string]string{"123": "abc"}, "string2string"))
fmt.Println(VerifyType(map[string]string{"123": "abc"}, "string2interface"))
Output:

true
false
true
false
true
false
true
false
true
false

Types

type Converter

type Converter struct {
	// contains filtered or unexported fields
}

Converter is used to convert the value by the Scan method. So you can use it as the argument of Rows.Scan() in sql.

func NewConverter

func NewConverter(kind Kind) Converter

NewConverter returns a Converter to convert a value to the type kind.

func (*Converter) Scan

func (c *Converter) Scan(src interface{}) error

Scan converts the value src.

func (Converter) Value

func (c Converter) Value() interface{}

Value returns the inner converted result.

type Deque

type Deque struct {
	// contains filtered or unexported fields
}

Deque implements an efficient double-ended queue.

Internally it is composed of a doubly-linked list (list.List) of blocks. Each block is a slice that holds 0 to blockLen items. The Deque starts with one block. Blocks are added to the front and back when the edge blocks fill up as items are pushed onto the deque. Edge blocks are removed when blocks become empty as items are popped off the Deque.

Only the front and back blocks may contain less than blockLen items. The first element in the Deque is d.blocks.Front().Value[d.frontIdx]. The last element in the Deque is d.blocks.Back().Value[d.backIdx].

This approach is more efficient than using a standard doubly-linked list for a queue because memory allocation is only required every blockLen items, instead of for each pushed item. Conversely, fewer memory deallocations are required when popping items. Bookkeeping overhead per item is also reduced.

Usage:

d := deque.New()
d.PushFront("foo")
d.PushBack("bar")
d.PushBack("123")
l := d.Len()          // l == 3
v, ok := d.PopFront() // v.(string) == "foo", ok == true
v, ok = d.PopFront()  // v.(string) == "bar", ok == true
v, ok = d.PopBack()   // v.(string) == "123", ok == true
v, ok = d.PopBack()   // v == nil, ok == false
v, ok = d.PopFront()  // v == nil, ok == false
l = d.Len()           // l == 0
Example
de := NewDeque()
de.PushBack(1)
de.PushBack(2)
de.PushBack(3)
de.PushFront("a")
de.PushFront("b")
de.PushFront("c")

de.Each(func(v interface{}) {
	fmt.Println(v)
})

fmt.Println(de.PopBack())
fmt.Println(de.PopFront())
Output:

c
b
a
1
2
3
3 true
c true

func NewDeque

func NewDeque() *Deque

NewDeque returns a new Deque instance.

func NewDequeWithMaxLen

func NewDequeWithMaxLen(maxLen int) *Deque

NewDequeWithMaxLen returns a new Deque instance which is limited to a certain length. Pushes which cause the length to exceed the specified size will cause an item to be dropped from the opposing side.

A maxLen of 0 means that there is no maximum length limit in place.

func (*Deque) Each

func (d *Deque) Each(f func(v interface{}))

Each will traverse each element then pass f.

func (*Deque) Len

func (d *Deque) Len() int

Len returns the number of items stored in the queue.

func (*Deque) PopBack

func (d *Deque) PopBack() (interface{}, bool)

PopBack removes an item from the back of the queue and returns it. The returned flag is true unless there were no items left in the queue.

func (*Deque) PopFront

func (d *Deque) PopFront() (interface{}, bool)

PopFront removes an item from the front of the queue and returns it. The returned flag is true unless there were no items left in the queue.

func (*Deque) PushBack

func (d *Deque) PushBack(item interface{})

PushBack adds an item to the back of the queue.

func (*Deque) PushFront

func (d *Deque) PushFront(item interface{})

PushFront adds an item to the front of the queue.

type Kind

type Kind int

Kind represents the kind of the converter.

const (
	Unknown Kind = iota
	Nil
	Bool
	Int
	Int8
	Int16
	Int32
	Int64
	Uint
	Uint8
	Uint16
	Uint32
	Uint64
	Float32
	Float64
	String
	Bytes
	Time        // For the format "YYYY-MM-DD HH:MM:SS"
	RFC3339Time // For the format time.RFC3339
)

Predefine some kinds.

type Set

type Set struct {
	// contains filtered or unexported fields
}

Set is a set type.

The element of the set must be hashable, such as int, string, array, etc. Notice: slice and map is not hashable.

The set supports the mixed types, but suggest to use the consistent type in a set.

Example
s1 := NewSet(1, 2, 3)
s2 := NewSet("a", "b", "c")

s1.Add(3, 4, 5)
s2.Add("c", "d", "e")
fmt.Println(s1.Size(), s1.Size())
fmt.Println(s1.Has(4), s1.Has(5), s1.Has(6), s2.Has("d"), s2.Has("e"), s2.Has("z"))
// Output:
// 5 5
// true true false true true false

s1.RemoveInts(1, 2, 9)
s2.RemoveStrings("a", "b", "z")
fmt.Println(s1.Size(), s2.Size())
fmt.Println(s1.Has(1), s1.Has(2), s2.Has("a"), s2.Has("b"))
// Output:
// 3 3
// false false false false

list1 := s1.List()
fmt.Println(list1[0])
fmt.Println(list1[1])
fmt.Println(list1[2])
// Unordered output:
// 3
// 4
// 5

list2 := s2.List()
fmt.Println(list2[0])
fmt.Println(list2[1])
fmt.Println(list2[2])
// Unordered output:
// c
// d
// e

union := s1.Union(s2)
diff := s1.Difference(s2)
inter := s1.Intersection(s2)
sdiff := s1.SymmetricDifference(s2)
fmt.Println(union.Size(), diff.Size(), inter.Size(), sdiff.Size())
// Output:
// 6 3 0 6

fmt.Println(union.Difference(s1).Equal(s2))
fmt.Println(union.Equal(sdiff))
// Output:
// true
// true

list := union.List()
fmt.Println(list[0])
fmt.Println(list[1])
fmt.Println(list[2])
fmt.Println(list[3])
fmt.Println(list[4])
fmt.Println(list[5])
// Unordered output:
// 3
// 4
// 5
// c
// d
// e

set := NewSet([2]int{1, 2}, [2]int{3, 4})
fmt.Println(set.Has([2]int{1, 2}))
fmt.Println(set.Has([2]int{2, 3}))
fmt.Println(set.Has([3]int{2, 3, 4}))
fmt.Println(set.Has([2]string{"a", "b"}))
// true
// false
// false
// false
Output:

5 5
true true false true true false
3 3
false false false false
3
4
5
c
d
e
6 3 0 6
true
true
3
4
5
c
d
e
true
false
false
false

func NewSet

func NewSet(elements ...interface{}) Set

NewSet returns a new Set.

If the element is string, it will ignore the empty string.

func NewSetFromInts

func NewSetFromInts(elements ...int) Set

NewSetFromInts returns a new Set.

func NewSetFromSet

func NewSetFromSet(sets ...Set) Set

NewSetFromSet returns a new Set.

func NewSetFromStrings

func NewSetFromStrings(elements ...string) Set

NewSetFromStrings returns a new Set.

It will ignore the empty string.

func (Set) Add

func (s Set) Add(elements ...interface{})

Add adds some elements into the set.

If the element is string, it will ignore the empty string.

func (Set) AddInts

func (s Set) AddInts(elements ...int)

AddInts adds some int elements into the set.

func (Set) AddStrings

func (s Set) AddStrings(elements ...string)

AddStrings adds some string elements into the set.

It will ignore the empty string.

func (Set) Clear

func (s Set) Clear()

Clear removes all the elements from the set.

func (Set) Copy

func (s Set) Copy() Set

Copy returns a copy of the current set.

func (Set) Difference

func (s Set) Difference(others ...Set) Set

Difference returns a new set with elements in the set that are not in the others.

func (Set) DifferenceUpdate

func (s Set) DifferenceUpdate(others ...Set)

DifferenceUpdate updates the set, removing the elements found in others.

func (Set) Equal

func (s Set) Equal(other Set) bool

Equal returns true if s == other.

func (Set) Has

func (s Set) Has(element interface{}) bool

Has returns true if the element is in the set. Or return false.

func (Set) Intersection

func (s Set) Intersection(others ...Set) Set

Intersection returns a new set with elements common to the set and all others.

func (Set) IntersectionUpdate

func (s Set) IntersectionUpdate(others ...Set)

IntersectionUpdate updates the set, keeping only elements found in it and all others.

func (Set) List

func (s Set) List() []interface{}

List converts the set to a list type.

func (Set) Pop

func (s Set) Pop() interface{}

Pop removes and returns an arbitrary element from the set. But return nil if the set is empty.

func (Set) Remove

func (s Set) Remove(elements ...interface{})

Remove removes the elements from the set.

func (Set) RemoveInts

func (s Set) RemoveInts(elements ...int)

RemoveInts removes the int elements from the set.

func (Set) RemoveStrings

func (s Set) RemoveStrings(elements ...string)

RemoveStrings removes the string elements from the set.

func (Set) Size

func (s Set) Size() int

Size returns the number of the elements in the set.

func (Set) SymmetricDifference

func (s Set) SymmetricDifference(other Set) Set

SymmetricDifference returns a new set with elements in either the set or other but not both.

func (Set) SymmetricDifferenceUpdate

func (s Set) SymmetricDifferenceUpdate(other Set)

SymmetricDifferenceUpdate updates the set, keeping only elements found in either set, but not in both.

func (Set) Union

func (s Set) Union(others ...Set) Set

Union returns a new set with elements from the set and all others.

func (Set) UnionUpdate

func (s Set) UnionUpdate(others ...Set)

UnionUpdate updates the set, adding the elements from all others.

func (Set) Walk

func (s Set) Walk(f func(interface{}))

Walk travels the elements of the set.

type VerifyFunc

type VerifyFunc func(value interface{}, _type string) bool

VerifyFunc is a function to verifty whether the type of a value is the given type, the first argument of which is the value, and the second of which is the given type.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL