cast

package
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2025 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Package cast provides safe, generic alternatives to Go's standard type assertion. It simplifies type conversions by offering convenient, single-expression functions that gracefully handle the `value, ok` idiom, avoiding panics on incorrect type assertions.

Usage

A common use case is safely dispatching events of different types:

type UserCreatedEvent struct{ UserID int }
type OrderPlacedEvent struct{ OrderID string }

func HandleEvent(event any) {
	if u, ok := cast.As[UserCreatedEvent](event); ok {
		processUserCreated(u)
		return
	}
	if o, ok := cast.As[OrderPlacedEvent](event); ok {
		processOrderPlaced(o)
		return
	}
	// Optionally, handle or log unknown event types.
}

Another simple example:

var myVal any = "hello world"

// Safely cast `myVal` to a string.
if str, ok := cast.As[string](myVal); ok {
	fmt.Printf("Successfully casted to string: %s\n", str)
}

// Attempt to cast to an incorrect type.
if _, ok := cast.As[int](myVal); !ok {
	fmt.Println("Failed to cast to int, as expected.")
}

For more details on specific functions, refer to the function documentation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Or

func Or[T any](v any, def T) T

Or attempts to perform a type assertion of v to type T. If the assertion is successful, it returns the converted value. If the assertion fails, it returns the provided default value `def`.

func OrZero

func OrZero[T any](v any) T

OrZero attempts to perform a type assertion of v to type T. If the assertion is successful, it returns the converted value. If the assertion fails, it returns the zero value of type T.

func Try

func Try[T any](v any) (T, bool)

Try attempts to perform a type assertion of v to type T. It is a direct, generic wrapper around Go's `value, ok` idiom. If the assertion is successful, it returns the converted value and true. If the assertion fails, it returns the zero value of T and false.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL