https://github.com/insei/cast
Cast is string casting library, support cast string to generic type, reflect type and value type
https://github.com/insei/cast
cast casting go golang string string-manipulation
Last synced: 3 months ago
JSON representation
Cast is string casting library, support cast string to generic type, reflect type and value type
- Host: GitHub
- URL: https://github.com/insei/cast
- Owner: Insei
- License: apache-2.0
- Created: 2024-05-22T07:59:11.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2024-07-08T20:07:40.000Z (10 months ago)
- Last Synced: 2025-01-03T00:14:16.088Z (4 months ago)
- Topics: cast, casting, go, golang, string, string-manipulation
- Language: Go
- Homepage:
- Size: 24.4 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: Readme.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://codecov.io/github/Insei/cast)
[](https://github.com/Insei/cast/actions/workflows/go.yml)
[](https://goreportcard.com/report/github.com/insei/cast)
[](https://godoc.org/github.com/insei/cast)
# 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.
```bash
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.
```go
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).
```go
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.
```go
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.
```go
date := time.Time{}
err := cast.ToFrom("2024-05-22T11:36:57+03:00", &date)
if err != nil {
panic(err)
}
```