Skip to content

Commit

Permalink
feat(misc/must): assertion on if a value is nil or a invalid value
Browse files Browse the repository at this point in the history
  • Loading branch information
saitofun committed May 29, 2024
1 parent e9a44ed commit 62e17b5
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
14 changes: 13 additions & 1 deletion misc/must/must.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package must

import "github.com/pkg/errors"
import (
"github.com/pkg/errors"

"github.com/xoctopus/x/reflectx"
)

func NoError(err error) {
if err != nil {
Expand Down Expand Up @@ -39,3 +43,11 @@ func BeTrueV[V any](v V, ok bool) V {
}
return v
}

func NotNilV[V any](v V) V {
rv := reflectx.Indirect(v)
if rv == reflectx.InvalidValue {
panic("must not nil: invalid value")
}
return v
}
34 changes: 34 additions & 0 deletions misc/must/must_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package must_test

import (
"fmt"
"reflect"

"github.com/pkg/errors"

"github.com/xoctopus/x/misc/must"
"github.com/xoctopus/x/ptrx"
)

func ReturnError() error {
Expand Down Expand Up @@ -113,3 +115,35 @@ func ExampleBeTrueWrap() {
// Output:
// must be true: required exists
}

func ExampleNotNilV() {
func() {
defer func() {
fmt.Println(recover())
}()
must.NotNilV((*int)(nil))
}()

func() {
defer func() {
fmt.Println(recover())
}()
must.NotNilV(any((*int)(nil)))
}()

func() {
defer func() {
fmt.Println(recover())
}()
fmt.Println(must.NotNilV(1))
fmt.Println(*must.NotNilV(ptrx.Ptr(1)))
must.NotNilV(reflect.TypeOf(nil))
}()

// Output:
// must not nil: invalid value
// must not nil: invalid value
// 1
// 1
// must not nil: invalid value
}

0 comments on commit 62e17b5

Please sign in to comment.