42

golang技巧-接口型函数

 5 years ago
source link: https://studygolang.com/articles/14034?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

接口型函数:指的是用函数实现接口,这样在调用的时候就会非常简便,这种函数为接口型函数,这种方式适用于只有一个函数的接口。

定义一个类型,这个类型只定义了函数的参数列表,函数参数列表与接口定义的方法一致:

type HandlerFunc func(k, v interface{})

然后这个类型去实现接口,实现的函数调用自己

func (hf HandlerFunc) Do(k, v interface{}) {
	hf(k, v)  // 接口的实现中调用本身。这样就使得可以用函数来实现接口功能,而不是定义类型并实现接口来实现接口功能
}

这样就可以用两种方法去实现接口功能

func Each(mp map[interface{}]interface{}, h Handler) { // 传入一个实现了Handler接口的类型的实例
}

func EachFunc(mp map[interface{}]interface{}, handlerFunc HandlerFunc)  { // 传入了一个参数列表为接口所需实现函数的
}

第二种方式可以只传入一个函数,只要求参数列表一致,函数名字可随便起,类型也不用新定义,用起来很方便。

完整代码如下;

package main

import "fmt"

type Handler interface {
	Do (k, v interface{})
}

type HandlerFunc func(k, v interface{})

func (hf HandlerFunc) Do(k, v interface{}) {
	hf(k, v)
}

func Each(mp map[interface{}]interface{}, h Handler) {
	if mp != nil && len(mp) > 0 {
		for k, v := range mp {
			h.Do(k, v)
		}
	}
}

func EachFunc(mp map[interface{}]interface{}, handlerFunc HandlerFunc)  {
	if mp != nil && len(mp) > 0 {
		for k, v := range mp {
			handlerFunc(k, v)
		}
	}
}

func selfInfo(k, v interface{}) {
	fmt.Printf("my name is %s, i am %d years old", k, v)
	fmt.Println()
}

func main() {
	mp := map[interface{}]interface{}{
		"gaoziwen":26,
		"zhangsan":27,
		"lisi":28,
	}

	f := selfInfo
	EachFunc(mp, f)
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK