Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: slices: convert one slice to another #64742

Closed
lmtyler opened this issue Dec 15, 2023 · 2 comments
Closed

proposal: slices: convert one slice to another #64742

lmtyler opened this issue Dec 15, 2023 · 2 comments
Labels
Milestone

Comments

@lmtyler
Copy link

lmtyler commented Dec 15, 2023

Proposal Details

Proposal Details
I would like to suggest a new method for slices that converts one slice to another slice

Addition: to slices/slices.go

// Convert transforms a []S1 into a []S2
// based on the provided mapping function.
[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, f func(E1) E2) S2 
func Convert[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, f func(E1) (E2, error)) (S2, error) {
        s2 := make([]S2, 0, len(s1))
	for i := range s1 {
                r, err := f(s1[i])
                if err != nil {
                  return nil, error
                }
		s2 = append(result, r)
	}
	return s2, nil
}

Example:

type Foo struct {
  A int
  B string
}
type Bar struct {
  C float
  D []rune
}

func TestConvert(t *testing.T) {
	x := []Foo{
	   {
	     A: 1,
	     B: "foo"
	   },
	   {
	     A: 100
	     B: "bar"
	   },
	}
      y := slices.Convert(x, func(f Foo) (Bar, error)){
         return &Bar{
           C: float(f.A)
           D: []rune(f.B)
         }, nil
      })
      if err != nil {
         t.Error(err)
      }
      for i, f := range x {
         if float(f.A) != y.C {
		t.Error("not equal")
	}
         if slices.Equal[]rune(f.B), y.D) {
		t.Error("not equal")
	}
      }
}
@gopherbot gopherbot added this to the Proposal milestone Dec 15, 2023
@randall77
Copy link
Contributor

This is going to be handled by the new iterator design. See #61897, particularly #61898's Map and #61899's Collect.

@seankhliao
Copy link
Member

Duplicate of #61898

@seankhliao seankhliao marked this as a duplicate of #61898 Dec 15, 2023
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Dec 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants