ptr

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 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

func To[T any](v any) *T

To converts an `any` value to a pointer of type *T. It handles three cases:

  1. If v is of type T, it returns a pointer to it (&v).
  2. If v is already of type *T, it returns v directly.
  3. Otherwise, it returns a new pointer to a zero value of T.

func ToVal

func ToVal[T any](v any) T

ToVal converts an `any` value to a value of type T. It handles three cases:

  1. If v is a non-nil pointer of type *T, it returns the dereferenced value.
  2. If v is of type T, it returns v directly.
  3. Otherwise, it returns the zero value of T.

func Val

func Val[T any](v *T) T

Val returns the value that the pointer v points to. If the pointer is nil, it safely returns the zero value of the type T. This avoids a panic when dereferencing a nil pointer.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL