Browse Source

Add `ToUUID` casting

This close #92
pull/93/head
erdaltsksn 4 years ago
parent
commit
6177c2cc1d
No known key found for this signature in database GPG Key ID: ACA574950443624F
4 changed files with 36 additions and 1 deletions
  1. +11
    -1
      cast.go
  2. +20
    -0
      caste.go
  3. +3
    -0
      go.mod
  4. +2
    -0
      go.sum

+ 11
- 1
cast.go View File

@@ -6,7 +6,11 @@
// Package cast provides easy and safe casting in Go.
package cast

import "time"
import (
"time"

"github.com/google/uuid"
)

// ToBool casts an interface to a bool type.
func ToBool(i interface{}) bool {
@@ -169,3 +173,9 @@ func ToDurationSlice(i interface{}) []time.Duration {
v, _ := ToDurationSliceE(i)
return v
}

// ToUUID casts an interface to a uint type.
func ToUUID(i interface{}) uuid.UUID {
v, _ := ToUUIDE(i)
return v
}

+ 20
- 0
caste.go View File

@@ -14,6 +14,8 @@ import (
"strconv"
"strings"
"time"

"github.com/google/uuid"
)

var errNegativeNotAllowed = errors.New("unable to cast negative value")
@@ -756,6 +758,24 @@ func ToUint8E(i interface{}) (uint8, error) {
}
}

// ToUUIDE casts an interface to a uint type.
func ToUUIDE(i interface{}) (uuid.UUID, error) {
i = indirect(i)
var b uuid.UUID

switch s := i.(type) {
case string:
return uuid.Parse(s)
case interface{}:
if str, err := ToStringE(s); err == nil {
return uuid.Parse(str)
}
return b, fmt.Errorf("unable to cast %#v of type %T to UUID", i, i)
default:
return b, fmt.Errorf("unable to cast %#v of type %T to UUID", i, i)
}
}

// From html/template/content.go
// Copyright 2011 The Go Authors. All rights reserved.
// indirect returns the value, after dereferencing as many times


+ 3
- 0
go.mod View File

@@ -2,6 +2,9 @@ module github.com/spf13/cast

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/google/uuid v1.1.1
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.2
)

go 1.13

+ 2
- 0
go.sum View File

@@ -1,5 +1,7 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=


Loading…
Cancel
Save