A simple, type-safe Go utility library for working with pointers using generics.
- Type-safe pointer operations using Go generics
- Zero dependencies
- Simple API with only three functions
- Well-documented with examples
go get github.com/sergei-bronnikov/go-pointerimport "github.com/sergei-bronnikov/go-pointer"Convert any value to a pointer. Useful when you need to pass a pointer to a literal or computed value.
// Convert string literal to pointer
name := gopointer.ToPointer("John Doe")
fmt.Println(*name) // Output: John Doe
// Convert number to pointer
age := gopointer.ToPointer(42)
fmt.Println(*age) // Output: 42
// Useful for optional struct fields
type User struct {
Name string
Email *string
}
user := User{
Name: "John",
Email: gopointer.ToPointer("john@example.com"),
}Dereference a pointer to get its value. Note: This function will panic if the pointer is nil.
str := "hello"
ptr := &str
value := gopointer.ToValue(ptr)
fmt.Println(value) // Output: helloSafely dereference a pointer with a fallback default value if the pointer is nil.
// With nil pointer
var ptr *string = nil
value := gopointer.ToValueOrDefault(ptr, "default")
fmt.Println(value) // Output: default
// With non-nil pointer
str := "hello"
ptr = &str
value = gopointer.ToValueOrDefault(ptr, "default")
fmt.Println(value) // Output: hello
// Useful for working with optional API fields
type Config struct {
Timeout *int
}
cfg := Config{}
timeout := gopointer.ToValueOrDefault(cfg.Timeout, 30)
fmt.Println(timeout) // Output: 30package main
import (
"fmt"
"github.com/sergei-bronnikov/go-pointer"
)
type UserProfile struct {
Username string
Email *string
Age *int
}
func main() {
// Create profile with optional fields
profile := UserProfile{
Username: "johndoe",
Email: gopointer.ToPointer("john@example.com"),
Age: nil,
}
// Safely access optional fields
email := gopointer.ToValueOrDefault(profile.Email, "no-email@example.com")
age := gopointer.ToValueOrDefault(profile.Age, 0)
fmt.Printf("Username: %s\n", profile.Username)
fmt.Printf("Email: %s\n", email)
fmt.Printf("Age: %d\n", age)
}Converts a value of any type to a pointer to that value.
Parameters:
value: The value to convert to a pointer
Returns:
- A pointer to the value
Dereferences a pointer and returns its value.
Parameters:
pointer: The pointer to dereference
Returns:
- The dereferenced value
Note: Panics if the pointer is nil.
Safely dereferences a pointer, returning a default value if the pointer is nil.
Parameters:
pointer: The pointer to dereferencedefaultValue: The value to return if the pointer is nil
Returns:
- The dereferenced value, or the default value if the pointer is nil
- Go 1.18 or higher (for generics support)
See LICENSE file for details.