为了账号安全,请及时绑定邮箱和手机立即绑定

调用泛型函数类型:无效操作:不能调用非函数 fn

调用泛型函数类型:无效操作:不能调用非函数 fn

Go
有只小跳蛙 2022-11-23 16:17:35
我将发布我目前正在处理的代码示例。我得到了错误:错误:无效操作:无法调用非函数 fn(MapFunc 约束的 MF 类型变量)是否可以使用包含不同函数签名的约束以这种方式使用?(如果可能的话,我想了解如何让我写的东西首先发挥作用。)这是示例:package mainimport "fmt"// MapFunc constraint used in Funcytype MapFunc interface {    func(s string, ss []string) []string | func(s string, ss []string) []bool}// MapFuncType used for Funcy return constrainttype MapFuncType interface {    string | bool}// Funcy preforms map operation on generic map functionsfunc Funcy[MF MapFunc, MFT MapFuncType](s string, ss []string, fn MF) []MFT {    return fn(s, ss)    // error: invalid operation: cannot call non-function fn (variable of type    // MF constrained by MapFunc)}// appendTo adds given string to the end of each index of given slice of strings// Ex. appendTo("_", []string{"append", "to"}) --> []string{"append_", "to_"}func appendTo(s string, ss []string) []string {    var slice []string    for _, v := range ss {        slice = append(slice, v+s)    }    return slice}// isMatch checks given string against each index in given string slice for a// match// Ex. isMatch("hi", []string{"hello", "hi"}) --> []bool{false, true}func isMatch(s string, ss []string) []bool {    var slice []bool    for _, v := range ss {        slice = append(slice, s == v)    }    return slice}func main() {    slice1 := []string{"append", "to"}    slice2 := []string{"hello", "hi"}    fmt.Println(Funcy(slice1, appendTo))    // want: []string{"append_", "to_"}    // got: error: cannot infer MFT    fmt.Println(Funcy(slice2, isMatch))    //[]bool{false, true}    // got: error: cannot infer MFT}
查看完整描述

1 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

当您将类型参数约束MF为 时MapFunc,您无法调用fn,因为 的MapFunc类型集中的函数类型没有相同的签名。它们有不同的返回类型[]string和[]bool.


所以fn有效类型的变量不支持被调用,你会得到(有点神秘的)错误信息“无法调用非函数 fn”。


更正式地说,只能调用具有类型函数核心类型MapFunc的值,但约束没有核心类型。


解决方法是参数化MapFunc并使用该类型参数作为返回值,这样在实例化时,它就会有一个核心类型:


type MapFunc[T MapFuncType] interface {

    func(s string, ss []string) []T

}

MFT并使用in实例化约束Funcy:


func Funcy[MF MapFunc[MFT], MFT MapFuncType](s string, ss []string, fn MF) []MFT {

    return fn(s, ss)

}

游乐场:https ://go.dev/play/p/q88aJLgnzXZ


查看完整回答
反对 回复 2022-11-23
  • 1 回答
  • 0 关注
  • 216 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信