dtdr84101
2019-07-04 13:40
浏览 97
已采纳

可以为函数类型创建方法吗?

I know methods can be created for specific types

Example

type MyFunc func() int

func (f MyFunc) eval() int {
    return f()
}

func main() {
   var randomFunction MyFunc = func() int {
      return 1;
  }

  fmt.Println(randomFunction.eval()) // prints 1
}

But randomFunction had to be declared as with MyFunc type. If the declaration looked like

randomFunction := func() int {
  return 1;
}

the method call wouldn't had worked.

My question is whether methods can be created for every function with func () int type, for example.

I know Go is not functional, nor does contain too many functional idioms, but the I'm looking for an approach similar to Haskell's show instance for functions:

instance Show (Int -> Int) where
   show op = show "Function with 1 Int param and Int return type"
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题