add Map method to a generic slice in go

496 Views Asked by At

I can't create a Map method for a generic stlice in go for fluent style programming (method chaining).

For example look at the code snippet I've created for the Filter method:

package main

import "fmt"

type Stream[T any] []T

type Consumer[T any] func(T)

type Predicate[T any] func(T) bool

func NewStream[T any](slice []T) Stream[T] {
    return Stream[T](slice)
}

func (s Stream[T]) ForEach(cons Consumer[T]) {
    for _, val := range s {
        cons(val)
    }
}

func (s Stream[T]) Filter(pred Predicate[T]) Stream[T] {
    res := []T{}

    s.ForEach(func(i T) {
        if pred(i) {
            res = append(res, i)
        }
    })

    return NewStream(res)
}

func main() {
    NewStream([]int{1, 4, 2, 6, 9}).
        Filter(func(i int) bool { return i%2 == 0 }).
        ForEach(func(i int) { fmt.Println(i) })
}

But it seems we can't add a Map method to Stream[T] like this:

func (s Stream[T]) Map[S any](f func(T) S) []S {
    // The implementation does not matter.
    return nil
}

This is the error:

$ go run main.go
# command-line-arguments
./main.go:39:23: syntax error: method must have no type parameters
0

There are 0 best solutions below