Golang泛型+可变参数函数

huangapple go评论65阅读模式
英文:

Golang Generic+Variadic Function

问题

在Golang中,如果有一些通用类型的函数,可以这样定义:

type Transformer[A, B any] func(A) (B, error)

要定义一个通用的可变参数高阶函数,可以组合这样的函数,可以使用以下方式:

func Compose[A, B, C, ..., N any](transformers ...Transformer[A, B], transformers2 ...Transformer[B, C], ..., transformersN ...Transformer[M, N]) Transformer[A, N]

这个函数接受多个参数,每个参数都是类型为Transformer[A, B]的函数。通过组合这些函数,它返回一个类型为Transformer[A, N]的函数。

英文:

In Golang having a number of functions of some generic type

type Transformer[A, B any] func(A)(B, error)

How to define a Generic Variadic high order function that could compose such functions in general something as

func Compose[A,B,C....N any](transformers... Transformer[A,B], Transformer[B,C]...Transformer[M,N]) Transformer[A,N]

答案1

得分: 2

在Go语言中,尚不支持泛型可变参数函数。然而,你可以通过使用可变参数和递归来实现类似的效果。

英文:

In Go, generic variadic functions are not yet supported. However, you can achieve a similar result by using variadic arguments and recursion.

答案2

得分: 0

我同意@Volker的观点;在Go语言中这样做是很愚蠢的。我建议你发布另一个问题,简要说明你实际尝试解决的问题,并看看是否有更符合惯用方式的解决方法。

话虽如此,只是为了好玩:

package main

import (
	"fmt"
)

type Composable[B, N any] func(in B) N

func Return[N any]() Composable[N, N] {
	return func(in N) N {
		return in
	}
}

func ToString[N any](next Composable[string, N]) Composable[int, N] {
	return func(in int) N {
		return next(fmt.Sprintf("%v", in))
	}
}

func Hello[N any](next Composable[string, N]) Composable[string, N] {
	return func(in string) N {
		return next(fmt.Sprintf("helloooo %s", in))
	}
}

func main() {
	f := ToString(Hello(Return[string]()))
	res := f(22)
	fmt.Printf("%v", res)
    // 输出:helloooo 22
}

明确一点,如果我在代码审查中看到这样的代码,我会非常担心。😕

英文:

I agree with @Volker; this is a silly thing to do in Go. I would suggest you post another question with a summary of the problem you're actually trying to solve with this construction and see if there's a way to solve you're problem that's more idiomatic.

All that being said, just for fun:

package main

import (
	"fmt"
)

type Composable[B, N any] func(in B) N

func Return[N any]() Composable[N, N] {
	return func(in N) N {
		return in
	}
}

func ToString[N any](next Composable[string, N]) Composable[int, N] {
	return func(in int) N {
		return next(fmt.Sprintf("%v", in))
	}
}

func Hello[N any](next Composable[string, N]) Composable[string, N] {
	return func(in string) N {
		return next(fmt.Sprintf("helloooo %s", in))
	}
}

func main() {
	f := ToString(Hello(Return[string]()))
	res := f(22)
	fmt.Printf("%v", res)
    // Output: helloooo 22
}

To be clear, if I saw this in a code review I would be very concerned.😝

huangapple
  • 本文由 发表于 2023年7月3日 14:35:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定