function也可以有method?

Effective Go 里的一个小节 Interfaces and methods (https://golang.org/doc/effective_go.html#interface_methods) 介绍了把 method 附加到 function 上的方法。

1. 首先,创建一种 type, 这种 type 是一个 function。

2. 既然有了一个type,那么当然就可以把一个method附加到这个type上。

3. 写一个 function 具体实现上述那个 type。

4. 利用类型转换,让 function 变成上述 type 那种类型,这样,自然就可以调用相应的 method 了。

我写了一个具体的小例子,注释里的序号对应上述步骤:

package main

import (
	"fmt"
	"strconv"
)

type Say func(string) // 1

func (say Say) MyMethod(i int) { // 2
	n := i + 1
	say(strconv.Itoa(n))
}

func say(s string) { // 3
	fmt.Println(s)
}

func main() {
	say("Hello!")
	Say(say).MyMethod(9) // 4
}

  

结果是,打印 Hello! 和 10。

posted @ 2017-03-23 20:49  AHUI-2017  阅读(181)  评论(0编辑  收藏  举报