0

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
Zeke Lu
  • 6,349
  • 1
  • 17
  • 23
Baron
  • 19
  • 2
  • 2
    Sorry - what is your question? You are getting `syntax error: method must have no type parameters` because Go does not (currently) "permit methods to declare type parameters that are specific to the method" (see [here](https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md#no-parameterized-methods) for some reasons and [this issue](https://github.com/golang/go/issues/49085) for a discussion). – Brits May 06 '23 at 21:23
  • My question was how to make map function like the filter function I've presented. It seems go doesn't support it. Thanks for the links – Baron May 06 '23 at 21:37
  • 1
    "fluent style programming" you mean method chaining? or something else? – erik258 May 06 '23 at 22:29
  • 1
    @erik258 It should be method chaining. I have edited the question and added the tag. I also added the error message from Brits's comment. – Zeke Lu May 07 '23 at 02:00

0 Answers0