本文介绍了new-ed结构的返回类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 例如,我有这个结构: pre $ c $ type $ Map Map Map结构{ nMap int //地图数量作业 nReduce int //减少作业的数量文件字符串//输入文件的名称 MasterAddress字符串 registerChannel chan字符串 DoneChannel chan bool alive bool l net.Listener stats * list.List //您需要保持最新的注册工作人员地图工作人员地图[string] * WorkerInfo //在这里添加任何附加状态} 然后我新的它是这样的: mr:= new(MapReduce) 然后我使用它: rpcs:= rpc.NewServer() rpcs.Register(mr) 我的问题是, code> rpc.Register 将接口作为参数。 http://golang.org/pkg/net/rpc/#Server 但是 mr 这里不是界面,为什么它是正确的? 谢谢 $ b $它确实需要一个空的接口类型接口{} ,任何类型都可以满足这个接口类型。 因此,您可以将 * MapReduce 传递给 Register(接口{}) code>方法。 从 spec接口类型: 一个类型实现了包含其方法子集的任何接口,因此可以实现多个不同的接口。 > 例如,所有类型都实现空接口: interface {} 记住,一旦它被传递,其 static 类型变成 interface {} 。 反思法则提及: 有人说Go的界面是动态类型的,但这是误导性的。 它们是静态类型的:一个接口类型的变量总是具有相同的静态类型,并且即使在运行时存储在接口变量中的值可能会改变类型,值将始终满足界面。 详情请参阅什么是golang中的 interface {} 的含义?。 For example, I have this struct: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}Then I new it like this:mr := new(MapReduce)Then I use it like this:rpcs := rpc.NewServer()rpcs.Register(mr)My question is ,, rpc.Register takes interface as argument. http://golang.org/pkg/net/rpc/#Server but mr here is not interface, why is it right?Thanks 解决方案 It does take an empty interface type interface{}, which is satisfied by any type.So you can pass a *MapReduce to the Register(interface{}) method.From spec interface type: A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface:interface{}Bit remember, once it is passed, its static type become interface{}.Law of reflection mentions: Some people say that Go's interfaces are dynamically typed, but that is misleading. They are statically typed: a variable of interface type always has the same static type, and even though at run time the value stored in the interface variable may change type, that value will always satisfy the interface. See more at "what is the meaning of interface{} in golang?". 这篇关于new-ed结构的返回类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 16:43