mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add Of and Unwrap
This commit is contained in:
@@ -1,8 +1,25 @@
|
||||
// Copyright 2023 dudaodong@gmail.com. All rights reserved.
|
||||
// Use of this source code is governed by MIT license.
|
||||
|
||||
// Package pointer contains some util functions to operate go pointer.
|
||||
package pointer
|
||||
|
||||
import "reflect"
|
||||
|
||||
// Of returns a pointer to the value `v`.
|
||||
// Play: todo
|
||||
func Of[T any](v T) *T {
|
||||
return &v
|
||||
}
|
||||
|
||||
// Unwrap returns the value from the pointer.
|
||||
// Play: todo
|
||||
func Unwrap[T any](p *T) T {
|
||||
return *p
|
||||
}
|
||||
|
||||
// ExtractPointer returns the underlying value by the given interface type
|
||||
// Play: todo
|
||||
func ExtractPointer(value any) any {
|
||||
t := reflect.TypeOf(value)
|
||||
v := reflect.ValueOf(value)
|
||||
|
||||
44
pointer/pointer_examples_test.go
Normal file
44
pointer/pointer_examples_test.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package pointer
|
||||
|
||||
import "fmt"
|
||||
|
||||
func ExampleOf() {
|
||||
result1 := Of(123)
|
||||
result2 := Of("abc")
|
||||
|
||||
fmt.Println(*result1)
|
||||
fmt.Println(*result2)
|
||||
|
||||
// Output:
|
||||
// 123
|
||||
// abc
|
||||
}
|
||||
|
||||
func ExampleUnwrap() {
|
||||
a := 123
|
||||
b := "abc"
|
||||
|
||||
result1 := Unwrap(&a)
|
||||
result2 := Unwrap(&b)
|
||||
|
||||
fmt.Println(result1)
|
||||
fmt.Println(result2)
|
||||
|
||||
// Output:
|
||||
// 123
|
||||
// abc
|
||||
}
|
||||
|
||||
func ExampleExtractPointer() {
|
||||
a := 1
|
||||
b := &a
|
||||
c := &b
|
||||
d := &c
|
||||
|
||||
result := ExtractPointer(d)
|
||||
|
||||
fmt.Println(result)
|
||||
|
||||
// Output:
|
||||
// 1
|
||||
}
|
||||
@@ -1,12 +1,32 @@
|
||||
package pointer
|
||||
|
||||
import (
|
||||
"github.com/duke-git/lancet/v2/internal"
|
||||
"testing"
|
||||
|
||||
"github.com/duke-git/lancet/v2/internal"
|
||||
)
|
||||
|
||||
func TestExtractPointer(t *testing.T) {
|
||||
func TestOf(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestOf")
|
||||
|
||||
result1 := Of(123)
|
||||
result2 := Of("abc")
|
||||
|
||||
assert.Equal(123, *result1)
|
||||
assert.Equal("abc", *result2)
|
||||
}
|
||||
|
||||
func TestUnwrap(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestUnwrap")
|
||||
|
||||
a := 123
|
||||
b := "abc"
|
||||
|
||||
assert.Equal(a, Unwrap(&a))
|
||||
assert.Equal(b, Unwrap(&b))
|
||||
}
|
||||
|
||||
func TestExtractPointer(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestExtractPointer")
|
||||
|
||||
a := 1
|
||||
|
||||
Reference in New Issue
Block a user