In Golang structure function, the transfer function of the interface

Structure function, the transfer function of the interface

Definition of a function type F., And interfaces implemented method A, and then calls itself in this method. This is converted in the other language function Go port A common technique (the same as defined Arguments Return Value F)

To achieve "callback" a dynamically generated, such as the cache, when the key does not exist, it is necessary to take data from a remote database or file and other data sources. So write the callback function can not die.

User-defined method callback functions, and therefore, the data structure in the cache, there is a member variable callback method.

The following code is an example.

type Getter interface {
	Get(key string)([]byte,error)
}

type GetterFunc func(key string)([]byte,error)

//
func (f GetterFunc) Get(key string)([]byte,error){
	return f(key)
}
//test
func TestGetterFunc_Get(t *testing.T) {
	var f Getter  = GetterFunc(func(key string) ([]byte,error) {
		return []byte(key),nil
	})

	expect := []byte("key")
	if v,_ := f.Get("key");!reflect.DeepEqual(v,expect){
		t.Error("callback failed")
	}
}

Guess you like

Origin www.cnblogs.com/Jun10ng/p/12616284.html