Skip to content

Latest commit

 

History

History
67 lines (66 loc) · 1.72 KB

File metadata and controls

67 lines (66 loc) · 1.72 KB

codecov build Goreport GoDoc

Cast

Cast is string casting library, support cast string to generic type, reflect type and value type.

Installation

Install via go get. Note that Go 1.18 or newer is required.

go get github.com/Insei/cast@latest

Contribution

Feel free to contribute

Supported types

(*)int
(*)int8
(*)int16
(*)int32
(*)int64
(*)uint
(*)uint8
(*)uint16
(*)uint32
(*)uint64
(*)float32
(*)float64
(*)bool
(*)string
(*)time.Time
(*)uuid.UUID (Google)

Examples

To[int] example.

valInt, err := cast.To[int]("56")
// or valPtrInt, err := To[*int]("56")
if err != nil {
	panic(err)
}

To[time.Time] example (supports strings only in time.RFC3339).

valTime, err := cast.To[time.Time]("2024-05-22T11:36:57+03:00")
// or valPtrTime, err := To[*time.Time]("2024-05-22T11:36:57+03:00")
if err != nil {
	panic(err)
}

ToReflect(string, reflect.Type) example.

timeType := reflect.TypeOf(time.Time{})
valTime, err := cast.ToReflect("2024-05-22T11:36:57+03:00", timeType)
// or valPtrTime, err := ToReflect("2024-05-22T11:36:57+03:00", reflect.PointerTo(timeType))
if err != nil {
	panic(err)
}

ToFrom(string, any) example.

date := time.Time{}
err := cast.ToFrom("2024-05-22T11:36:57+03:00", &date)
if err != nil {
	panic(err)
}