You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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")
}
}
}
The text was updated successfully, but these errors were encountered:
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
Example:
The text was updated successfully, but these errors were encountered: