Can't figure out how to create an All() iter.Seq[T] method

170 views
Skip to first unread message

Mark

unread,
Mar 13, 2024, 8:32:45 AM3/13/24
to golang-nuts
I've been trying to learn how to create an `All() iter.Seq[T]` method for a simple set type (a map wrapper):


It won't work in the playground of course, but when I do:
`GOEXPERIMENT=rangefunc go run .`
using Go 1.22 I get this error:
```
cannot use func(yield func(int, T) bool) {…} (value of type func(yield func(int, T) bool)) as iter.Seq[T] value in return statement
```
Can someone help me get this right please?

```
package main

import (
"cmp"
"fmt"
"iter"
)

func main() {
s := New(5, 10, 15, 20, 35)
for v := range s.All() {
fmt.Println(v)
}
}

type Set[T cmp.Ordered] map[T]struct{}

func New[T cmp.Ordered](elements ...T) Set[T] {
set := make(Set[T], len(elements))
for _, element := range elements {
set[element] = struct{}{}
}
return set
}

func (me Set[T]) All() iter.Seq[T] {
return func(yield func(int, T) bool) { // ERROR
n := 0
for key := range me {
if !yield(n, key) {
return
}
n++
}
}
}
```

Sebastien Binet

unread,
Mar 13, 2024, 9:22:06 AM3/13/24
to Mark, golang-nuts
hi Mark,

On Wed Mar 13, 2024 at 13:32 CET, 'Mark' via golang-nuts wrote:
> I've been trying to learn how to create an `All() iter.Seq[T]` method
> for a
> simple set type (a map wrapper):
>
> playground <https://go.dev/play/p/wtWvvTf33AF?v=gotip>
>
> It won't work in the playground of course, but when I do:
> `GOEXPERIMENT=rangefunc go run .`
> using Go 1.22 I get this error:
> ```
> cannot use func(yield func(int, T) bool) {…} (value of type func(yield
> func(int, T) bool)) as iter.Seq[T] value in return statement
> ```
> Can someone help me get this right please?

IIRC,

```
return func(yield func(int, T) bool) { ... }
```
is for iter.Seq2[int,T]

if you want iter.Seq[T] you should write:

```
return func (yield func(T) bool) { ... }
```
(and adapt accordingly)

hth,
-s

Mark

unread,
Mar 13, 2024, 9:51:59 AM3/13/24
to golang-nuts
Thank you, that solved the problem.
Reply all
Reply to author
Forward
0 new messages