Documentation
¶
Overview ¶
Package ptr provides generic utility functions for working with pointers. It simplifies common operations such as creating a pointer from a literal value or safely dereferencing a pointer that might be nil.
This package is particularly useful in contexts where you need to assign a pointer to a struct field, but you only have a literal value (e.g., a string, an integer, or a boolean).
Example:
// Without ptr package port := 8080 config := &ServerConfig{ Port: &port, } // With ptr package config := &ServerConfig{ Port: ptr.Of(8080), // Cleaner and more concise }
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Of ¶
func Of[T any](v T) *T
Of returns a pointer to the given value v. This is a convenient helper for creating a pointer to a literal or a variable in a single expression, often used for struct field initialization.
Example:
config := &MyConfig{ Timeout: ptr.Of(5*time.Second) }
func To ¶
To converts an `any` value to a pointer of type *T. It handles three cases:
- If v is of type T, it returns a pointer to it (&v).
- If v is already of type *T, it returns v directly.
- Otherwise, it returns a new pointer to a zero value of T.
Types ¶
This section is empty.