英文:
what is the return type of new-ed struct?
问题
例如,我有这个结构体:
type MapReduce struct {
nMap int // Map 任务的数量
nReduce int // Reduce 任务的数量
file string // 输入文件的名称
MasterAddress string
registerChannel chan string
DoneChannel chan bool
alive bool
l net.Listener
stats *list.List
// 需要保持更新的已注册工作节点的映射
Workers map[string]*WorkerInfo
// 在这里添加任何其他状态
}
然后我这样创建它:
mr := new(MapReduce)
然后我这样使用它:
rpcs := rpc.NewServer()
rpcs.Register(mr)
我的问题是,rpc.Register
接受接口作为参数。http://golang.org/pkg/net/rpc/#Server
但是这里的 mr
不是接口,为什么这样是正确的?
谢谢
英文:
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
答案1
得分: 3
interface{}
是一个空接口类型,可以被任何类型满足。
因此,你可以将 *MapReduce
传递给 Register(interface{})
方法。
根据接口类型规范:
> 一个类型可以实现其方法的任何子集,因此可以实现多个不同的接口。
例如,所有类型都实现了空接口:
interface{}
但要记住,一旦传递后,它的静态类型变为 interface{}
。
反射定律提到:
> 有人说Go的接口是动态类型,但这是误导。
>
> 它们是静态类型的:接口类型的变量始终具有相同的静态类型,即使在运行时存储在接口变量中的值可能会更改类型,该值仍将满足接口。
更多信息请参见“在Go中interface{}
的含义是什么?”。
英文:
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?".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论