From fd55be28fa73c507f9fee3956b1d06679318b00d Mon Sep 17 00:00:00 2001 From: Mike Helmick Date: Mon, 2 Oct 2023 21:31:32 -0700 Subject: [PATCH] Map ptr (#5) * add map conversion * map to pointers * lint --- slice/map.go | 11 +++++++++++ slice/map_test.go | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/slice/map.go b/slice/map.go index 2ed4606..2f66759 100644 --- a/slice/map.go +++ b/slice/map.go @@ -29,3 +29,14 @@ func Map[T any, R any](in []T, fn MapFn[T, R]) []R { } return rtn } + +// MapToPtr transforms a slice into a slice of pointers +// to the same elements. +func MapToPtr[T any](in []T) []*T { + rtn := make([]*T, len(in)) + for i, e := range in { + e := e + rtn[i] = &e + } + return rtn +} diff --git a/slice/map_test.go b/slice/map_test.go index 7ed255b..37b7795 100644 --- a/slice/map_test.go +++ b/slice/map_test.go @@ -71,3 +71,23 @@ func TestMap(t *testing.T) { t.Fatalf("mismatch (-want, +got):\n%s", diff) } } + +func TestMapPtr(t *testing.T) { + t.Parallel() + in := []Person{ + { + Name: "Alice", + Age: 30, + }, + { + Name: "Bob", + Age: 31, + }, + } + + got := slice.MapToPtr(in) + want := []*Person{&in[0], &in[1]} + if diff := cmp.Diff(want, got); diff != "" { + t.Fatalf("mismatch (-want, +got):\n%s", diff) + } +}