Thursday, September 12, 2024
HomeGolangGenerics With closure return - Getting Assist

Generics With closure return – Getting Assist


package deal predominant

import "fmt"

func chunker[T any]() func([]T, int) [][]T {
	return func(ar []T, measurement int) [][]T {
		var finalAr [][]T
		for i := 0; i < len(ar); i += measurement {
			finish := i + measurement
			if finish > len(ar) {
				finish = len(ar)
			}
			finalAr = append(finalAr, ar[i:end])
		}
		return finalAr
	}
}
func predominant() {
	xI := []int{1, 2, 3, 0, 0, 5, 6, 4, 7, 8, 9, 10}
	fmt.Println(chunker()(xI, 3))
}

This throws

./prog.go:20:21: can not infer T (prog.go:5:14)

Its equal with out closure return works nice

package deal predominant

import "fmt"

func chunker[T any](ar []T, measurement int) [][]T {
	var finalAr [][]T
	for i := 0; i < len(ar); i += measurement {
		finish := i + measurement
		if finish > len(ar) {
			finish = len(ar)
		}
		finalAr = append(finalAr, ar[i:end])
	}
	return finalAr
}
func predominant() {
	xI := []int{1, 2, 3, 0, 0, 5, 6, 4, 7, 8, 9, 10}
	xS := []string{"a", "b", "c", "c", "d", "e", "f", "g", "h"}

	fmt.Println(chunker(xI, 3))
	fmt.Println(chunker(xS, 4))
}

Provides this

[[1 2 3] [0 0 5] [6 4 7] [8 9 10]]
[[a b c c] [d e f g] [h]]

Which is predicted

How can I make the closure one work

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments