new-ed结构的返回类型是什么?

时间:2014-05-18 16:14:04

标签: go

例如,我有这个结构:

type MapReduce struct {
    nMap            int    // Number of Map jobs
    nReduce         int    // Number of Reduce jobs
    file            string // Name of input file
    MasterAddress   string
    registerChannel chan string
    DoneChannel     chan bool
    alive           bool
    l               net.Listener
    stats           *list.List

    // Map of registered workers that you need to keep up to date
    Workers map[string]*WorkerInfo

    // add any additional state here
}

然后我像这样新来了:

mr := new(MapReduce)

然后我像这样使用它:

rpcs := rpc.NewServer()
rpcs.Register(mr)

我的问题是,rpc.Register将接口作为参数。 http://golang.org/pkg/net/rpc/#Servermr这里不是界面,为什么不对?

由于

1 个答案:

答案 0 :(得分:3)

它采用空接口类型interface{},任何类型都满足。

因此,您可以将*MapReduce传递给Register(interface{})方法。

来自spec interface type

  

类型实现包含其方法的任何子集的任何接口,因此可以实现几个不同的接口   例如,所有类型都实现空接口:

interface{}

请记住,一旦通过,其静态类型将变为interface{} Law of reflection提及:

  

有些人说Go的界面是动态输入的,但这是误导性的。

     

它们是静态类型的:接口类型的变量始终具有相同的静态类型,即使在运行时存储在接口变量中的值可能会更改类型,该值也始终满足接口。

请参阅" what is the meaning of interface{} in golang?"。