Documentation
¶
Overview ¶
Package typutil provides flexible type conversion and function calling utilities for Go.
This library offers several key features:
1. Type Conversion:
- Convert between different Go types with automatic handling of common conversions
- Support for primitive types, structs, slices, maps, and custom types
- Convert between structs with different field types but matching names
2. Function Wrapping:
- Wrap Go functions to support flexible argument handling
- Automatic context detection and passing
- Default parameter values
- Type conversion for function arguments
- JSON input handling
3. Validation:
- Validate struct field values using tag-based validators
- Register custom validators for specific types
- Support for complex validation rules with parameters
4. Pointer and Interface Utilities:
- Check for nil values in interfaces and pointers
- Flatten nested pointers
- Create pointers to values
The package is designed to make working with dynamic types and function calls in Go easier and more flexible, while maintaining type safety where possible.
Package typutil provides utilities for type conversion and function argument handling in Go.
Index ¶
- Constants
- Variables
- func As[T any](v any) (T, error)
- func AsBool(v any) bool
- func AsByteArray(v any) ([]byte, bool)
- func AsFloat(v any) (float64, bool)
- func AsInt(v any) (int64, bool)
- func AsNumber(v any) (any, bool)
- func AsString(v any) (string, bool)
- func AsUint(v any) (uint64, bool)
- func Assign(dst, src any) error
- func AssignReflect(vdst, vsrc reflect.Value) error
- func BaseType(v any) any
- func Call[T any](s *Callable, ctx context.Context, arg ...any) (T, error)
- func DeepClone[T any](v T) T
- func DeepCloneReflect(src reflect.Value) reflect.Value
- func Equal(a, b any) bool
- func Flatten(a any) any
- func FormatSize(x uint64) string
- func IsNil(v any) bool
- func Math(mathop string, a, b any) (any, bool)
- func OffsetGet(ctx context.Context, v any, offset string) (any, error)
- func SetValidator[T any](validator string, fnc func(T) error)
- func SetValidatorArgs(validator string, fnc any)
- func StrictArgs(c *Callable)
- func ToType(ref, v any) (any, bool)deprecated
- func Validate(obj any) error
- type AssignableTo
- type Callable
- func (s *Callable) ArgKind(n int) reflect.Kind
- func (s *Callable) Call(ctx context.Context) (any, error)
- func (s *Callable) CallArg(ctx context.Context, arg ...any) (any, error)
- func (s *Callable) IsStringArg(n int) bool
- func (s *Callable) String() string
- func (s *Callable) WithDefaults(args ...any) *Callable
- type RawJsonMessage
- type Signed
- type Unsigned
Constants ¶
const Required requiredArg = 1
Required is a sentinel value that marks a parameter as required when using WithDefaults. When specified as a default value, it indicates that the parameter must be provided by the caller and cannot be defaulted.
Variables ¶
var ( // Assignment-related errors ErrAssignDestNotPointer = errors.New("assign destination must be a pointer") ErrAssignImpossible = errors.New("the requested assign is not possible") ErrNilPointerRead = errors.New("attempt to read from a nil pointer") ErrDestinationNotAddressable = errors.New("assign: destination cannot be addressed") ErrInvalidSource = errors.New("assign source is not valid") // Validation-related errors ErrEmptyValue = errors.New("validator: value must not be empty") ErrStructPtrRequired = errors.New("parameter must be a pointer to a struct") // Function calling errors ErrMissingArgs = errors.New("missing arguments") ErrTooManyArgs = errors.New("too many arguments") ErrDifferentType = errors.New("wrong type in function call") // Offset-related errors ErrBadOffset = errors.New("bad offset type") )
Error constants for various operations in the typutil package. These errors are returned from functions like Assign, Func, and validation methods.
Functions ¶
func As ¶ added in v0.2.5
As converts a value to the specified type T, with type conversion as needed.
This generic function provides a type-safe way to convert values between different types. It leverages the type conversion capabilities of Assign but returns the result as the requested type rather than modifying an existing variable.
Type Parameters:
- T: The target type to convert to
Parameters:
- v: The value to convert
Returns:
- The converted value as type T
- An error if the conversion cannot be performed
Example:
// Convert string to int
i, err := As[int]("42") // i is 42
// Convert between struct types
type Person struct {Name string; Age int}
type User struct {Name string; Age string}
p := Person{Name: "Alice", Age: 30}
u, err := As[User](p) // u is User{Name: "Alice", Age: "30"}
func AsBool ¶
AsBool converts any value to a boolean using an intuitive conversion strategy.
Conversion rules: - bool: used directly - numbers: true if non-zero, false if zero - strings: true if non-empty and not "0", false otherwise - bytes/buffer: true if length > 1 or not "0", false otherwise - maps/slices/collections: true if not empty, false otherwise - nil: false
This is useful when working with user inputs, configuration values, or any scenario where values of different types need to be interpreted as booleans.
func AsByteArray ¶ added in v0.1.14
AsByteArray converts any value to a byte slice ([]byte) using flexible conversion rules.
It returns the converted byte slice and a boolean indicating success (true) or failure (false).
Conversion rules: - Strings: converted to UTF-8 byte representation - Byte slices: returned directly - Buffer types: contents extracted as bytes - Numeric types: converted to their binary representation (big-endian) - Booleans: true → [1], false → [0] - nil: returns nil - Complex/Float types: binary representation using encoding/binary - Other types: string representation as bytes, but marked as non-direct conversion (false)
This is useful for serialization, hashing, or when working with binary protocols.
func AsFloat ¶
AsFloat converts any value to a float64 using flexible type conversion rules.
It returns the converted value and a boolean indicating success (true) or failure (false).
Conversion rules: - Float types: directly converted to float64 - Integer types: converted to equivalent float64 - Unsigned integers: converted to equivalent float64 - Strings: parsed as floating point numbers (returns false if not a valid number) - nil: returns 0.0 - Other types: attempts conversion via AsInt as a fallback
This is useful for normalizing input data from various sources into consistent floating point values.
func AsInt ¶
AsInt converts any value to an int64 using flexible type conversion rules.
It returns the converted value and a boolean indicating success (true) or failure (false).
Conversion rules: - Integer types: directly converted to int64 - Unsigned integers: converted to int64 (returns false if too large for int64) - Booleans: true → 1, false → 0 - Floating point: rounded to nearest integer (returns false if not a whole number) - Strings: parsed as integers (returns false if not a valid integer) - Byte slices: converted to string and parsed - Byte buffers: contents parsed as integers - nil: returns 0
This is useful for normalizing input data from various sources into consistent integer values.
func AsNumber ¶
AsNumber converts any value to the most appropriate numeric type (int64, uint64, or float64).
It intelligently chooses the numeric type that best represents the input value: - Most integers are represented as int64 - Large unsigned integers (that don't fit in int64) are represented as uint64 - Decimal numbers are represented as float64 - String representations of numbers are parsed to the appropriate type
It returns the converted value (as interface{}) and a boolean indicating success (true) or failure (false).
This is particularly useful when you need to convert a value to a number, but don't know exactly which numeric type would be most appropriate.
func AsString ¶ added in v0.1.2
AsString converts any value to a string using flexible conversion rules.
It returns the converted string and a boolean indicating success (true) or failure (false).
Conversion rules: - String types: used directly - Byte slices and buffers: converted to strings - Numeric types: formatted as base-10 strings - Booleans: true → "1", false → "0" - Other types: uses fmt.Sprintf("%v", value) but returns false to indicate non-direct conversion
This is useful when you need to display or serialize values of various types as strings.
func AsUint ¶
AsUint converts any value to a uint64 using flexible type conversion rules.
It returns the converted value and a boolean indicating success (true) or failure (false).
Conversion rules: - Integer types: converted to uint64 (returns false if negative) - Unsigned integers: directly converted to uint64 - Booleans: true → 1, false → 0 - Floating point: rounded to nearest integer (returns false if negative or not a whole number) - Strings: parsed as unsigned integers (returns false if not a valid unsigned integer) - nil: returns 0
This is useful for normalizing input data from various sources into consistent unsigned integer values.
func Assign ¶ added in v0.1.5
Assign sets dst to the value of src, performing type conversion as needed.
This is the main entry point for the type conversion system in typutil. It handles automatic conversion between various Go types, including: - Primitive types (string, int, float, bool) - Pointers and interfaces - Slices and maps - Structs (using field names or JSON tags for matching) - Custom types that implement valueScanner or AssignableTo interfaces
For container types (slices, maps, structs), a shallow copy is performed.
Parameters:
- dst: A pointer to the destination value (must be a non-nil pointer)
- src: The source value to assign from
Returns:
- An error if the assignment cannot be performed, such as when:
- The destination is not a pointer
- The types are incompatible and cannot be converted
- The source value is invalid
Example:
// Convert between compatible types
var i int
err := Assign(&i, "42") // i becomes 42
// Convert between struct types with matching fields
type Person struct {
Name string
Age int
}
type User struct {
Name string
Age string
}
p := Person{Name: "Alice", Age: 30}
var u User
err := Assign(&u, p) // u becomes User{Name: "Alice", Age: "30"}
Note that unlike json.Unmarshal or similar functions, Assign requires a pointer to the destination value, not the destination value itself.
func AssignReflect ¶ added in v0.1.19
AssignReflect assigns a value from one reflect.Value to another, with type conversion.
This is the reflection-based version of Assign that works directly with reflect.Value objects. It's used internally by the library and is also available for advanced use cases where you're already working with reflection.
Parameters:
- vdst: The destination reflect.Value
- vsrc: The source reflect.Value
Returns:
- An error if the assignment cannot be performed
This function handles unwrapping interface values, dealing with pointers, and finding the appropriate conversion function for the types involved.
func BaseType ¶ added in v0.1.4
BaseType unwraps values to their underlying primitive types.
It performs the following conversions: - For custom types (e.g., `type CustomString string`), returns the underlying primitive (string) - For json.RawMessage, attempts to unmarshal the content - For reflect.Value, extracts the actual value - For pointers and interfaces, dereferences them to their underlying values - For numeric types, converts to their Go primitives (int64, uint64, float64, etc.)
Example:
type MyString string var x MyString = "hello" result := BaseType(x) // returns "hello" as a string, not MyString
This is useful when working with custom types and wanting to normalize them to standard Go types.
func Call ¶ added in v0.2.19
Call invokes a Callable and returns a strongly typed result.
This generic function provides type safety for calling wrapped functions. It automatically converts the return value to the requested type T, which eliminates the need for type assertions in the calling code.
Parameters:
- s: The Callable to invoke
- ctx: The context to pass to the function
- arg: The arguments to pass to the function
Returns:
- A value of type T (the function's return value)
- An error if:
- The function call failed (see CallArg for possible errors)
- The function's return value could not be converted to type T
Example:
func add(a, b int) int { return a + b }
callable := Func(add)
// Get a strongly typed result
result, err := Call[int](callable, ctx, 5, 10) // result is an int, not an interface{}
// This will fail with ErrDifferentType
result, err := Call[string](callable, ctx, 5, 10) // err indicates type mismatch
Generic functions like this are particularly useful in code that needs to maintain type safety while still supporting flexible function calling patterns.
func DeepClone ¶ added in v0.2.9
func DeepClone[T any](v T) T
DeepClone performs a deep duplication of the provided argument, returning a newly created independent copy. All nested pointers, slices, maps, and structs are recursively cloned.
Circular references are handled correctly - if a structure contains pointers that form a cycle, the cloned structure will have equivalent cycles pointing to the cloned values.
Struct fields tagged with `clone:"-"` are skipped during deep cloning and retain their shallow-copied values. This is useful for fields like database connections, mutexes, or other resources that should not be duplicated:
type MyStruct struct {
Data []byte
Conn *sql.DB `clone:"-"` // will not be deep cloned
}
func DeepCloneReflect ¶ added in v0.2.9
DeepCloneReflect performs a deep duplication of the provided reflect.Value. See DeepClone for details on behavior.
func Flatten ¶ added in v0.2.8
Flatten unwraps a value by removing all layers of pointers and interfaces, returning the underlying value.
This is particularly useful when working with values that might be wrapped in multiple layers of pointers or interfaces, and you want to get to the actual value.
Examples:
s := "hello"
ptr := &s
ptrptr := &ptr
Flatten(ptrptr) // returns "hello" as a string
var nilPtr *string = nil
Flatten(nilPtr) // returns nil
var iface interface{} = &s
Flatten(iface) // returns "hello" as a string
The function preserves the nil status of values - if any pointer in the chain is nil, nil will be returned.
func FormatSize ¶ added in v0.2.22
FormatSize formats a byte size as a human-readable string with appropriate units.
This function converts a raw byte count into a formatted string using binary prefixes (KiB, MiB, GiB, etc.) according to IEC standards (powers of 1024).
The formatted string includes: - The integer part - A decimal point - Two decimal places - The appropriate binary unit (B, KiB, MiB, GiB, TiB, PiB, EiB)
For values less than 1024 bytes, the function returns a simple byte count without decimals.
Parameters:
- x: The size in bytes to format
Returns:
- A human-readable string representing the size
Examples:
- FormatSize(0) → "0 B"
- FormatSize(1023) → "1023 B"
- FormatSize(1024) → "1.00 KiB"
- FormatSize(1536) → "1.50 KiB"
- FormatSize(1048576) → "1.00 MiB"
- FormatSize(1073741824) → "1.00 GiB"
func IsNil ¶ added in v0.2.8
IsNil recursively checks if a value is nil, following pointers and interfaces to their underlying values.
This function provides a more robust nil check than the builtin `== nil` comparison, which only works for direct nil values. IsNil can detect "deeply nested" nil values, such as: - A nil pointer or interface - A pointer to a nil pointer - An interface containing a nil pointer - A pointer to an interface containing a nil pointer, etc.
It also correctly identifies nil channels, maps, slices, and functions.
Example:
var x *string // x is nil
IsNil(x) // returns true
var y **string // y points to a nil *string
IsNil(y) // returns true
var z interface{} = x // z is an interface containing a nil pointer
IsNil(z) // returns true
For non-nillable types (like int, string, etc.), it always returns false.
func Math ¶ added in v0.1.16
Math performs a mathematical operation on two values of any type and returns the result.
The function works by: 1. Converting both inputs to numeric types using AsNumber() 2. Determining the correct type of operation based on the numeric types 3. Applying the appropriate operation and returning the result
Parameters:
- mathop: The operation to perform as a string. Supported operations: "+", "-", "*", "/", "^", "%", "&", "|"
- a, b: The operands for the operation. Can be of any type that can be converted to a number
Returns:
- The result of the operation as int64, uint64, or float64 depending on the inputs
- A boolean indicating success (true) or failure (false)
Examples:
result, ok := Math("+", 40, 2) // result = int64(42), ok = true
result, ok := Math("+", 40.5, 1.5) // result = float64(42.0), ok = true
result, ok := Math("/", 84, 2) // result = int64(42), ok = true
result, ok := Math("+", "40", "2") // result = int64(42), ok = true
result, ok := Math("invalid", 1, 2) // result = 0, ok = false
Notes:
- If either input has a float type, the result will be a float64
- Division by zero will cause a panic - it's recommended to check for zero divisors before calling
- Bitwise operations (^, %, &, |) return NaN when operating on floats
func OffsetGet ¶ added in v0.2.6
OffsetGet returns v[offset] dealing with various case of figure. ctx will be passed to some methods handling it
func SetValidator ¶ added in v0.1.6
SetValidator registers a typed validation function with the given name.
This function provides a type-safe way to register validators. The validator function must accept a single argument of type T and return an error.
Parameters:
- validator: The name of the validator (used in struct tags)
- fnc: The validation function that checks values of type T
This function should typically be called in init() to register validators before they are used.
Example:
func init() {
// Register a validator that ensures strings are not empty
SetValidator("required", func(s string) error {
if s == "" {
return errors.New("value is required")
}
return nil
})
// Register a validator that ensures integers are positive
SetValidator("positive", func(i int) error {
if i <= 0 {
return errors.New("value must be positive")
}
return nil
})
}
func SetValidatorArgs ¶ added in v0.1.13
SetValidatorArgs registers a validation function that may accept additional arguments.
Unlike SetValidator, this function accepts any function type as long as it takes at least one argument (the value to validate) and returns an error. Additional arguments can be specified in the validator tag after an equals sign.
Parameters:
- validator: The name of the validator (used in struct tags)
- fnc: The validation function, which must:
- Take at least one argument (the value to validate)
- Return an error (or nil if validation passes)
Example:
func init() {
// Register a validator that ensures strings have a minimum length
SetValidatorArgs("minlength", func(s string, minLen int) error {
if len(s) < minLen {
return fmt.Errorf("must be at least %d characters long", minLen)
}
return nil
})
}
// Then use it in a struct tag:
type User struct {
Password string `validator:"minlength=8"` // Password must be at least 8 characters
}
Panics if:
- fnc is not a function
- fnc does not accept at least one argument
func StrictArgs ¶ added in v0.2.24
func StrictArgs(c *Callable)
StrictArgs is a functional option for Func that enforces strict type checking of arguments. When enabled, arguments passed to the function must match the expected types exactly, rather than using the more flexible conversion via the Assign function.
Example:
// Without StrictArgs, "42" would be converted to int(42) f := Func(myIntFunc) // Allows "42" to be passed to an int parameter f2 := Func(myIntFunc, StrictArgs) // Requires an actual int, rejects "42"
func ToType
deprecated
added in
v0.1.17
ToType converts a value to the same type as a reference value.
It examines the type of the reference value (ref) and attempts to convert the input value (v) to that same type. This is useful when you need to ensure type compatibility between values.
Parameters:
- ref: The reference value whose type will be used as the target type
- v: The value to convert to the target type
Returns:
- The converted value with the same type as ref
- A boolean indicating success (true) or failure (false)
Deprecated: Use the generic As[T](v) function instead, which provides type safety at compile time.
func Validate ¶ added in v0.1.10
Validate checks if a struct meets all validation rules defined in its field tags.
This function processes all fields in a struct that have "validator" tags and runs the appropriate validation functions on them. If any validation fails, an error is returned with details about which field failed and why.
Parameters:
- obj: A pointer to the struct to validate. Using a pointer is required so that validators can potentially modify values during validation.
Returns:
- nil if all validations pass
- An error if any validation fails, formatted as "on field X: error details"
- ErrStructPtrRequired if obj is not a pointer to a struct
Example:
type User struct {
Name string `validator:"required"`
Email string `validator:"required,email"`
Password string `validator:"minlength=8"`
}
user := &User{Name: "Alice", Email: "invalid", Password: "123"}
err := Validate(user) // Returns error: "on field Email: invalid email format"
Validations are applied in the order they appear in the tag, from left to right. If a field has no validator tag or the tag is empty, it is not validated.
Types ¶
type AssignableTo ¶ added in v0.2.18
AssignableTo is an interface that can be implemented by objects able to assign themselves to values. Do not use Assign() inside AssignTo or you risk generating an infinite loop.
This looks a bit like sql's Valuer, except instead of a returning a any interface, the parameter is a pointer to the target type. Typically, Unmarshal will be used in here.
type Callable ¶ added in v0.2.19
type Callable struct {
// contains filtered or unexported fields
}
Callable represents a wrapped function that can be called with flexible argument handling. It provides several enhancements over standard Go function calls:
1. Context parameter detection - automatically detects and handles context.Context parameters 2. Type conversion - automatically converts arguments to the required parameter types 3. Default values - allows specifying default values for parameters 4. Variadic support - handles variadic functions (functions with ...T parameters) 5. JSON deserialization - can handle input from JSON
This type is not typically constructed directly but through the Func() function.
func Func ¶ added in v0.2.19
Func wraps a Go function as a Callable object, enabling flexible argument handling.
The wrapped function can have several forms: - Standard function: func(a, b, c) result - Context-aware function: func(ctx context.Context, a, b, c) result - Variadic function: func(a, b, ...c) result - Error-returning function: func(a, b) (result, error) - Any combination of the above
The returned Callable provides several enhancements: - Automatic conversion of argument types using Assign - Support for default parameter values (via WithDefaults) - Automatic handling of context parameters - JSON input parsing from context - Variadic function support
Parameters:
- method: The function to wrap (can also be a *Callable to apply additional options)
- options: Optional configuration options (e.g., StrictArgs)
Returns:
- A Callable object that wraps the function
Example:
func Add(a, b int) int { return a + b }
// Create a Callable that allows flexible type conversion
callable := Func(Add)
// Call with arguments that will be automatically converted
result, err := callable.CallArg(ctx, 5, "10") // result = 15
// Or with generic type inference
result, err := Call[int](callable, ctx, 5, "10") // result = 15, strongly typed
func (*Callable) ArgKind ¶ added in v0.2.19
ArgKind returns the reflect.Kind for the nth argument of the callable.
This method provides type information about function parameters without needing to use reflection directly. It's useful for implementing custom argument handling or validation logic.
Parameters:
- n: The zero-based index of the argument to check
Returns:
- The reflect.Kind of the argument's type
- reflect.Invalid if n is out of bounds
Example:
callable := Func(func(name string, age int, valid bool) {})
kind := callable.ArgKind(0) // reflect.String
kind = callable.ArgKind(1) // reflect.Int
kind = callable.ArgKind(2) // reflect.Bool
kind = callable.ArgKind(3) // reflect.Invalid (out of bounds)
func (*Callable) Call ¶ added in v0.2.19
Call invokes the function without explicit arguments, looking for input from context if needed.
This method is particularly useful when working with API handlers or middleware where the arguments need to be parsed from a request body or context.
If the function requires arguments (has parameters), Call will: 1. Look for a value stored under "input_json" in the context 2. If found, parse it as JSON and pass it as arguments to the function 3. For multiple parameters, the JSON should be an array with one element per parameter 4. For a single parameter, the JSON can be any value that's convertible to that parameter type
Parameters:
- ctx: The context to pass to the function (and to extract arguments from if needed)
Returns:
- The value returned by the function (or nil if it returns nothing)
- An error if the function call fails or returns an error
Example:
// Function that adds two numbers
func add(a, b int) int { return a + b }
callable := Func(add)
// Store JSON input in context
ctx := context.WithValue(context.Background(), "input_json", json.RawMessage(`[5, 10]`))
// Call the function using arguments from context
result, _ := callable.Call(ctx) // result = 15
func (*Callable) CallArg ¶ added in v0.2.19
CallArg calls the function with explicitly provided arguments.
This is the core method for invoking a wrapped function. It handles: - Converting arguments to the correct parameter types - Adding the context parameter if needed - Supplying default values for missing arguments (if WithDefaults was used) - Handling variadic arguments - Processing return values including errors
Parameters:
- ctx: The context to pass to the function (if it accepts one)
- arg: The arguments to pass to the function
Returns:
- The value returned by the function (or nil if it returns nothing)
- An error if:
- Not enough arguments are provided (and no defaults are available)
- Too many arguments are provided to a non-variadic function
- An argument can't be converted to the expected parameter type
- The function call itself returns an error
Example:
// Function that adds two numbers
func add(a, b int) int { return a + b }
callable := Func(add)
// Call with properly typed arguments
result, _ := callable.CallArg(ctx, 5, 10) // result = 15
// Call with arguments that need conversion
result, _ := callable.CallArg(ctx, "5", 10.0) // result = 15
// When using defaults, you can omit some arguments
callable = callable.WithDefaults(typutil.Required, 10)
result, _ := callable.CallArg(ctx, 5) // result = 15
func (*Callable) IsStringArg ¶ added in v0.2.19
IsStringArg returns true if the nth argument of the callable is a string, or a type related to string.
This is a utility method for quickly checking if an argument is string-based, which is useful when implementing custom argument handling logic.
Parameters:
- n: The zero-based index of the argument to check
Returns:
- true if the argument is a string type
- false otherwise (including when the index is out of bounds)
Example:
callable := Func(func(name string, age int) {})
isString := callable.IsStringArg(0) // true
isString = callable.IsStringArg(1) // false
func (*Callable) String ¶ added in v0.2.25
String returns a string representation of the function's signature.
This provides a human-readable view of the function's parameter types, including the variadic parameters if present. The context parameter is not included in this representation.
The format is similar to a Go function signature:
func(type1, type2, ...type3)
This is useful for debugging and logging purposes.
func (*Callable) WithDefaults ¶ added in v0.2.23
WithDefaults creates a new Callable with default argument values.
Default values are used when a call to CallArg doesn't provide enough arguments. This enables creating functions where some parameters are optional.
Parameters:
- args: Default values for each parameter. Use typutil.Required for parameters that must be provided by the caller.
Returns:
- A new Callable with the specified default values
Panics if:
- Not enough default arguments are provided
- Too many default arguments are provided for a non-variadic function
- A default value cannot be converted to the expected parameter type
Example:
// Original function
func myFunc(a, b, c int) int { return a + b + c }
// Create a Callable with defaults for parameters
f := Func(myFunc).WithDefaults(typutil.Required, typutil.Required, 42)
// Call with only the required parameters (c uses default value)
result, _ := f.CallArg(context.Background(), 10, 20) // equivalent to myFunc(10, 20, 42)
// You can also provide all parameters, overriding the defaults
result, _ := f.CallArg(context.Background(), 10, 20, 30) // equivalent to myFunc(10, 20, 30)
This pattern is especially useful for creating API handlers where some parameters are optional.
type RawJsonMessage ¶ added in v0.2.18
type RawJsonMessage []byte
RawJsonMessage is similar to json.RawMessage, but also implements additional functionality.
This type represents a raw JSON message as a byte slice. It provides: 1. Standard JSON marshaling/unmarshaling (like json.RawMessage) 2. The ability to assign its value to another variable via pjson.Unmarshal
RawJsonMessage is particularly useful when working with the Callable.Call method, which can extract JSON data from context and use it as function arguments.
func (RawJsonMessage) AssignTo ¶ added in v0.2.18
func (m RawJsonMessage) AssignTo(v any) error
AssignTo unmarshals the raw JSON message into the provided value.
This method uses pjson.Unmarshal (an enhanced JSON unmarshaler) to parse the raw JSON data and assign it to the target value. It's useful for converting JSON data to Go types, particularly when working with function arguments in the Callable.Call method.
Parameters:
- v: The target value to unmarshal the JSON into (passed by reference)
Returns:
- An error if the JSON parsing fails
func (RawJsonMessage) MarshalJSON ¶ added in v0.2.18
func (m RawJsonMessage) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface.
This method simply returns the raw JSON bytes, allowing the JSON data to be embedded directly within another JSON structure.
func (*RawJsonMessage) UnmarshalJSON ¶ added in v0.2.18
func (m *RawJsonMessage) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface.
This method stores the raw JSON bytes without parsing them, which allows deferring the actual JSON parsing until it's needed.
type Signed ¶ added in v0.2.17
Signed represents all signed integer types in Go. It includes both built-in types and user-defined types that have a signed integer as their underlying type. The tilde (~) symbol indicates that this interface matches both the specific type and any type derived from it.
type Unsigned ¶ added in v0.2.17
Unsigned represents all unsigned integer types in Go. It includes both built-in types and user-defined types that have an unsigned integer as their underlying type. The tilde (~) symbol indicates that this interface matches both the specific type and any type derived from it.