Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func P ¶
func P[T any](t T) *T
P returns a pointer to a new copy of the value v.
This is a generic function that works with any type. It creates a copy of the provided value and returns a pointer to this copy. The value is stored in the heap, not the stack.
Parameters:
- t: The value to create a pointer to. Can be of any type, including primitive types, structs, or interfaces.
Returns:
- *T: A pointer to a new copy of the value t.
Thread Safety:
This function is thread-safe as it doesn't access or modify any shared state.
Performance Considerations:
Creating a pointer with P() allocates memory on the heap. For performance-critical code paths where many pointers are created in tight loops, consider reusing a single variable and taking its address instead.
Examples:
Basic usage with a string:
str := "hello"
strPtr := ptr.P(str)
// Now strPtr is *string pointing to a copy of "hello"
With structs:
type User struct {
Name *string
Age *int
}
user := User{
Name: ptr.P("Alice"),
Age: ptr.P(30),
}
Common pattern for API parameters:
client.UpdateConfig(&api.Config{
Timeout: ptr.P(60),
Retries: ptr.P(3),
})
func PositiveOr ¶
PositiveOr returns *p if p is non-nil and *p > 0, otherwise returns fallback. Useful for optional config values where zero/negative means "use default".
func SafeDeref ¶
func SafeDeref[T any](p *T, fallback ...T) T
SafeDeref returns the value pointed to by p or a fallback value if p is nil. When p is nil and no fallback is provided, it returns the zero value for type T.
The function accepts any type T through its generic parameter. The fallback parameter is variadic for convenience, but only the first value is used if multiple are provided.
SafeDeref is particularly useful when working with optional values from APIs, database results, or configurations, where nil checks would otherwise clutter the code. It helps avoid nil pointer panics without sacrificing readability.
For types with reference semantics (maps, slices), the zero value is nil, not an initialized empty container.
Example usage:
s := "hello"
fmt.Println(ptr.SafeDeref(&s)) // Prints: hello
var nilStr *string
fmt.Println(ptr.SafeDeref(nilStr)) // Prints: "" (zero value)
fmt.Println(ptr.SafeDeref(nilStr, "default")) // Prints: default
// In a function handling a struct with pointer fields
func processConfig(cfg *Config) {
timeout := ptr.SafeDeref(cfg.Timeout, 30)
retries := ptr.SafeDeref(cfg.Retries, 3)
// Continue with non-nil values
}
SafeDeref is safe for concurrent use as it performs no mutation of shared state and makes no allocations beyond those needed for the return value.
Types ¶
This section is empty.