Documentation
¶
Overview ¶
Package erasure provides utilities for type erasure and type-safe conversion between generic types and the any type. This is useful when working with heterogeneous collections or when interfacing with APIs that require type erasure.
The package provides functions to:
- Erase typed values to any (via pointers)
- Unerase any values back to their original types
- Safely unerase with error handling
- Convert type-safe functions to erased functions
Example usage:
// Basic erasure and unerasure erased := erasure.Erase(42) value := erasure.Unerase[int](erased) // value == 42 // Safe unerasure with error handling result := erasure.SafeUnerase[int](erased) // result is Either[error, int] // Function erasure typedFunc := strconv.Itoa erasedFunc := erasure.Erase1(typedFunc) result := erasedFunc(erasure.Erase(42)) // returns erased "42"
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Erase ¶
Erase converts a variable of type T to an any by returning a pointer to that variable. This allows type-safe storage and retrieval of values in heterogeneous collections.
The value is stored as a pointer, which means the type information is preserved and can be recovered using Unerase or SafeUnerase.
Example:
erased := Erase(42) // erased is any, but internally holds *int
func Erase0 ¶
Erase0 converts a type-safe nullary function into an erased function. The resulting function returns an erased value.
Example:
typedFunc := func() int { return 42 }
erasedFunc := Erase0(typedFunc)
result := erasedFunc() // returns erased 42
func Erase1 ¶
Erase1 converts a type-safe unary function into an erased function. The resulting function takes an erased argument and returns an erased value.
Example:
typedFunc := strconv.Itoa erasedFunc := Erase1(typedFunc) result := erasedFunc(Erase(42)) // returns erased "42"
func Erase2 ¶
Erase2 converts a type-safe binary function into an erased function. The resulting function takes two erased arguments and returns an erased value.
Example:
typedFunc := func(x, y int) int { return x + y }
erasedFunc := Erase2(typedFunc)
result := erasedFunc(Erase(10), Erase(32)) // returns erased 42
func SafeUnerase ¶
SafeUnerase converts an erased variable back to its original value with error handling. Returns Either[error, T] where Left contains an error if the type assertion fails, and Right contains the unerased value if successful.
This is the safe alternative to Unerase that doesn't panic on type mismatch.
Example:
erased := Erase(42) result := SafeUnerase[int](erased) // result is Right(42) wrongType := SafeUnerase[string](erased) // wrongType is Left(error) with message about type mismatch
Types ¶
This section is empty.