typeutil

typeutil detects nil through interfaces, obtains zero values generically, dereferences pointers safely, and converts booleans to integers without a branch.

Part of nurago, a collection of independent Go packages for backend services.

import "github.com/tecnickcom/nurago/pkg/typeutil"

Package typeutil detects nil through interfaces, obtains zero values generically, dereferences pointers safely, and converts booleans to integers without a branch.

  • [IsNil]: reflection-based nil check that handles all nilable kinds (chan, func, interface, map, pointer, slice, unsafe pointer) and the untyped nil case, including a nil concrete pointer wrapped in a non-nil interface that v == nil misses.
  • [IsZero]: returns true when the value equals the zero value for its type (empty string, 0, nil pointer, false), without requiring a comparable constraint.
  • [Zero]: returns the zero value for any type T.
  • [Value]: dereferences a pointer, returning the zero value of T when the pointer is nil.
  • [BoolToInt]: converts a bool to 0 or 1 using the pattern the Go compiler optimizes to a single MOVBLZX instruction.

Usage

// Nil detection through an interface:
var p *MyStruct
var i any = p
typeutil.IsNil(i) // true, whereas i == nil is false

// Zero value inferred from an existing value, as a sentinel return:
func check[T any](v T) (T, error) {
	if !valid(v) {
		return typeutil.Zero(v), errInvalid
	}
	return v, nil
}

// Safe pointer dereference:
var timeout *time.Duration
d := typeutil.Value(timeout) // 0, no panic

// Branch-free bool-to-int:
score += typeutil.BoolToInt(isBonus) * bonusPoints

When To Use

  • Generic code must detect nil through an interface, where == nil is not enough.
  • You need the zero value of a type parameter.

Example

var nilChan chan int

v := typeutil.IsNil(nilChan)
fmt.Println(v)

// Output:
// true

Full source is in example_typeutil_test.go. More runnable examples are on pkg.go.dev.

Dependencies

This package reaches no external module: it uses only the Go standard library.