cast

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Package cast provides safe, generic alternatives to Go's standard type assertion.

This package simplifies type assertions by providing convenient, single-expression functions that handle the `value, ok` idiom in different ways, such as returning a default value or a zero value upon failure.

Example:

var myVal any = "hello"

// Standard Go type assertion
str, ok := myVal.(string)
if !ok {
	str = "default"
}

// With cast package - cleaner and more concise
str = cast.Or(myVal, "default")

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