Skip to content

Commit

Permalink
Map ptr (#5)
Browse files Browse the repository at this point in the history
* add map conversion

* map to pointers

* lint
  • Loading branch information
mikehelmick authored Oct 3, 2023
1 parent 5d86d04 commit fd55be2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions slice/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
20 changes: 20 additions & 0 deletions slice/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit fd55be2

Please # to comment.