go利用(*interface{})(nil)传递参数类型

原创文章转载请注明出处

最近阅读Martini的源码,读到了inject这部分,injectMartini的代码中无处不在,是Martini框架的绝对核心。

先看看injector类型的声明:

1
2
3
4
elm复制代码type injector struct {       
values map[reflect.Type]reflect.Value
parent Injector
}

撇开 parent不看,values是一个映射表,用于保存注入的参数,它是一个用reflect.Type当键、reflect.Value为值的map。

parent Injector又是什么鬼?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
reasonml复制代码// Injector represents an interface for mapping and injecting dependencies into structs
// and function arguments.
type Injector interface {
Applicator
Invoker
TypeMapper
// SetParent sets the parent of the injector. If the injector cannot find a
// dependency in its Type map it will check its parent before returning an
// error.
SetParent(Injector)
}

// Applicator represents an interface for mapping dependencies to a struct.
type Applicator interface {
// Maps dependencies in the Type map to each field in the struct
// that is tagged with 'inject'. Returns an error if the injection
// fails.
Apply(interface{}) error
}

// Invoker represents an interface for calling functions via reflection.
type Invoker interface {
// Invoke attempts to call the interface{} provided as a function,
// providing dependencies for function arguments based on Type. Returns
// a slice of reflect.Value representing the returned values of the function.
// Returns an error if the injection fails.
Invoke(interface{}) ([]reflect.Value, error)
}

// TypeMapper represents an interface for mapping interface{} values based on type.
type TypeMapper interface {
// Maps the interface{} value based on its immediate type from reflect.TypeOf.
Map(interface{}) TypeMapper
// Maps the interface{} value based on the pointer of an Interface provided.
// This is really only useful for mapping a value as an interface, as interfaces
// cannot at this time be referenced directly without a pointer.
MapTo(interface{}, interface{}) TypeMapper
// Provides a possibility to directly insert a mapping based on type and value.
// This makes it possible to directly map type arguments not possible to instantiate
// with reflect like unidirectional channels.
Set(reflect.Type, reflect.Value) TypeMapper
// Returns the Value that is mapped to the current type. Returns a zeroed Value if
// the Type has not been mapped.
Get(reflect.Type) reflect.Value
}

Injector是注入接口声明的组合,我们先关注TypeMapper这个接口,从源码可以得知Map和MapTo是用来映射数据类型和数据到values map[reflect.Type]reflect.Value的方法。

Map方法相对来说比较简单,利用反射获取对象的type。

1
2
3
4
stylus复制代码func (i *injector) Map(val interface{}) TypeMapper {
i.values[reflect.TypeOf(val)] = reflect.ValueOf(val)
return i
}

现在我们先假设参数中有多个string时,values map[reflect.Type]reflect.Value这个map只会保存最后一个string的映射,那我们该如何处理才能完整的保存所有的string参数呢?

考虑interface类型在底层的实现(type,data),inject库实现了一个从interface指针中获取类型的函数InterfaceOf,而MapTo则利用InterfaceOf来获取传入的数据类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
stylus复制代码func InterfaceOf(value interface{}) reflect.Type {       
t := reflect.TypeOf(value)

for t.Kind() == reflect.Ptr {
t = t.Elem()
}

if t.Kind() != reflect.Interface {
panic("Called inject.InterfaceOf with a value that is not a pointer to an interface. (*MyInterface)(nil)")
}
return t
}

func (i *injector) MapTo(val interface{}, ifacePtr interface{}) TypeMapper {
i.values[InterfaceOf(ifacePtr)] = reflect.ValueOf(val)
return i
}

简直是神来之笔,再找个别人的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
go复制代码package main

import (
"fmt"
"github.com/codegangsta/inject"
)

type SpecialString interface{}

func main() {
fmt.Println(inject.InterfaceOf((*interface{})(nil)))
fmt.Println(inject.InterfaceOf((*SpecialString)(nil)))
}

输出

1
2
haxe复制代码interface {}
main.SpecialString

看到了吗?指向接口的空指针,虽然data是nil,但是我们只要它的type。分步解释一下:

1
2
3
4
5
6
7
8
9
stylus复制代码//以(*SpecialString)(nil)为例
t := reflect.TypeOf(value) //t是*main.SpecialString,t.Kind()是ptr,t.Elem()是main.SpecialString
for t.Kind() == reflect.Ptr { //循环判断,也许是指向指针的指针
t = t.Elem() //Elem returns a type's element type.
}
if t.Kind() != reflect.Interface {
... //如果不是Interface类型,报panic
}
return t //返回(*SpecialString)(nil)的元素原始类型

interface{}是什么,在go里面interface{}就是万能的Anyinject利用了(*interface{})(nil)携带数据类型的特点,只用一个空指针就搞定了数据类型的传输,而且扩展了同类型数据的绑定。

让我们到martini.go去看看这个注入是怎么用的吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
stylus复制代码// Martini represents the top level web application. inject.Injector methods can be invoked to map services on a global level.
type Martini struct {
inject.Injector
handlers []Handler
action Handler
logger *log.Logger
}

// New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used.
func New() *Martini {
m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)}
m.Map(m.logger)
m.Map(defaultReturnHandler())
return m
}

func (m *Martini) createContext(res http.ResponseWriter, req *http.Request) *context {
c := &context{inject.New(), m.handlers, m.action, NewResponseWriter(res), 0}
c.SetParent(m)
c.MapTo(c, (*Context)(nil))
c.MapTo(c.rw, (*http.ResponseWriter)(nil))
c.Map(req)
return c
}

自定义的Martini结构体包含了inject.Injector接口,所以可以很方便的注入logger。后续Invoke中间件的时候,自然就可以通过InjectorGet方法获取logger对象。context则使用了MapTo方法注入了Contexthttp.ResponseWriter这两个接口类型。

那么Invoke的时候又是如何调用函数并且注入参数的呢?请移步《Invoke如何动态传参》

我是咕咕鸡,一个还在不停学习的全栈工程师。热爱生活,喜欢跑步,家庭是我不断向前进步的动力。

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%