【问题标题】:what is the return type of new-ed struct?新结构的返回类型是什么?
【发布时间】:2014-05-19 00:39:08
【问题描述】:

例如,我有这个结构:

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/#Server 但是mr这里不是接口,为什么是对的?

谢谢

【问题讨论】:

    标签: go


    【解决方案1】:

    它确实需要一个空的接口类型interface{},它可以满足任何类型。

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

    来自spec interface type

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

    interface{}
    

    记住,一旦通过,它的static类型变成interface{}
    Law of reflection提:

    有人说 Go 的接口是动态类型的,但这是误导。

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

    在“what is the meaning of interface{} in golang?”查看更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 2016-10-06
      • 2018-04-04
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多