Documentation
¶
Overview ¶
Package pointer contains generic pointer helper functions
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Coalesce ¶
func Coalesce[T any](p *T, v T) T
Coalesce returns *p if p is not nil, otherwise v.
Example ¶
package main
import (
"fmt"
"github.com/carlmjohnson/pointer"
)
func main() {
var np *int
fmt.Println(pointer.Coalesce(np, 1))
np = new(int)
fmt.Println(pointer.Coalesce(np, 1))
}
Output: 1 0
func Deref ¶
func Deref[T any](p *T) T
Deref returns *p if p is not nil, otherwise the zero value of T.
Example ¶
package main
import (
"fmt"
"github.com/carlmjohnson/pointer"
)
func main() {
var np *int
fmt.Println(pointer.Deref(np))
one := 1
np = &one
fmt.Println(pointer.Deref(np))
}
Output: 0 1
func First ¶
func First[T any](ptrs ...*T) *T
First returns the first non-nil pointer it is passed.
Example ¶
package main
import (
"fmt"
"github.com/carlmjohnson/pointer"
)
func main() {
type config struct{ string }
userInput := func() *config {
return nil
}
someConfig := pointer.First(
userInput(),
&config{"default config"},
)
fmt.Println(someConfig)
}
Output: &{default config}
func New ¶
func New[T any](value T) *T
New allocates a new variable of a given value and returns a pointer to it.
Example ¶
package main
import (
"fmt"
"github.com/carlmjohnson/pointer"
)
func main() {
strptr1 := pointer.New("meaning of life")
strptr2 := pointer.New("meaning of life")
fmt.Println(strptr1 != strptr2)
fmt.Println(*strptr1 == *strptr2)
intp1 := pointer.New(42)
intp2 := pointer.New(42)
fmt.Println(intp1 != intp2)
fmt.Println(*intp1 == *intp2)
type MyFloat float64
fp := pointer.New[MyFloat](42)
fmt.Println(fp != nil)
fmt.Println(*fp == 42)
}
Output: true true true true true true
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.