From 871b028e3401f77e0f0aa868ce3e8fd9396370a9 Mon Sep 17 00:00:00 2001 From: tx7do Date: Sun, 7 Apr 2024 13:19:53 +0800 Subject: [PATCH] feat: returns a pointer to the provided value use template function. --- trans/to.go | 18 ++++++++++++++++++ trans/to_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 trans/to.go create mode 100644 trans/to_test.go diff --git a/trans/to.go b/trans/to.go new file mode 100644 index 0000000..ef383f6 --- /dev/null +++ b/trans/to.go @@ -0,0 +1,18 @@ +//go:build go1.18 +// +build go1.18 + +package trans + +// Ptr returns a pointer to the provided value. +func Ptr[T any](v T) *T { + return &v +} + +// SliceOfPtrs returns a slice of *T from the specified values. +func SliceOfPtrs[T any](vv ...T) []*T { + slc := make([]*T, len(vv)) + for i := range vv { + slc[i] = Ptr(vv[i]) + } + return slc +} diff --git a/trans/to_test.go b/trans/to_test.go new file mode 100644 index 0000000..928921b --- /dev/null +++ b/trans/to_test.go @@ -0,0 +1,30 @@ +//go:build go1.18 +// +build go1.18 + +package trans + +import "testing" + +func TestPtr(t *testing.T) { + b := true + pb := Ptr(b) + if pb == nil { + t.Fatal("unexpected nil conversion") + } + if *pb != b { + t.Fatalf("got %v, want %v", *pb, b) + } +} + +func TestSliceOfPtrs(t *testing.T) { + arr := SliceOfPtrs[int]() + if len(arr) != 0 { + t.Fatal("expected zero length") + } + arr = SliceOfPtrs(1, 2, 3, 4, 5) + for i, v := range arr { + if *v != i+1 { + t.Fatal("values don't match") + } + } +}