Skip to content

Pointer

pointer contains some util functions to operate go pointer.

Source:

Usage:

go
import (
    "github.com/duke-git/lancet/v2/pointer"
)

Index

Documentation

Of

Returns a pointer to the pass value `v`.

Signature:

go
func Of[T any](v T) *T

Example:Run

go
package main

import (
    "fmt"
    "github.com/duke-git/lancet/v2/pointer"
)

func main() {
    result1 := pointer.Of(123)
    result2 := pointer.Of("abc")

    fmt.Println(*result1)
    fmt.Println(*result2)

    // Output:
    // 123
    // abc
}

Unwrap

Returns the value from the pointer.

Signature:

go
func Unwrap[T any](p *T) T

Example:Run

go
package main

import (
    "fmt"
    "github.com/duke-git/lancet/v2/pointer"
)

func main() {
    a := 123
    b := "abc"

    result1 := pointer.Unwrap(&a)
    result2 := pointer.Unwrap(&b)

    fmt.Println(result1)
    fmt.Println(result2)

    // Output:
    // 123
    // abc
}

UnwrapOr

Returns the value from the pointer or fallback if the pointer is nil.

Signature:

go
UnwrapOr[T any](p *T, fallback T) T

Example:Run

go
package main

import (
    "fmt"
    "github.com/duke-git/lancet/v2/pointer"
)

func main() {
	a := 123
	b := "abc"

	var c *int
	var d *string

	result1 := pointer.UnwrapOr(&a, 456)
	result2 := pointer.UnwrapOr(&b, "abc")
	result3 := pointer.UnwrapOr(c, 456)
	result4 := pointer.UnwrapOr(d, "def")

	fmt.Println(result1)
	fmt.Println(result2)
	fmt.Println(result3)
	fmt.Println(result4)

	// Output:
	// 123
	// abc
	// 456
	// def
}

UnwrapOrDefault

Returns the value from the pointer or the default value if the pointer is nil.

Signature:

go
UnwrapOrDefault[T any](p *T) T

Example:Run

go
package main

import (
    "fmt"
    "github.com/duke-git/lancet/v2/pointer"
)

func main() {
	a := 123
	b := "abc"

	var c *int
	var d *string

	result1 := pointer.UnwrapOrDefault(&a)
	result2 := pointer.UnwrapOrDefault(&b)
	result3 := pointer.UnwrapOrDefault(c)
	result4 := pointer.UnwrapOrDefault(d)

	fmt.Println(result1)
	fmt.Println(result2)
	fmt.Println(result3)
	fmt.Println(result4)

	// Output:
	// 123
	// abc
	// 0
	//
}

ExtractPointer

Returns the underlying value by the given interface type

Signature:

go
func ExtractPointer(value any) any

Example:Run

go
package main

import (
    "fmt"
    "github.com/duke-git/lancet/v2/pointer"
)

func main() {
    a := 1
    b := &a
    c := &b
    d := &c

    result := pointer.ExtractPointer(d)

    fmt.Println(result)

    // Output:
    // 1
}