英文:
What does new applied to an interface mean?
问题
我理解,如果T
是一个结构体,那么这相当于创建一个空的结构体(有意义的空值):
t := new(T)
然而,给定以下代码片段:
type Burper interface {burp() int}
b := new(Burper)
创建了什么,以及使用new
创建接口的用途是什么?
英文:
I understand that if T
is a struct, then this amounts to creating an empty struct (sensible empty values)::
t := new(T)
However, given the following snippet::
type Burper interface {burp() int}
b := new(Burper)
What is created & what is the usefulness of new'ing an interface ?
答案1
得分: 7
这只是创建了一个指向Burper接口的指针。由于几乎没有合理的用途来指向一个接口,这在Go语言中是有效的,但在实践中是无害且无用的。
b
是一个指针,指向Burper的零值,即nil。
请参考http://play.golang.org/p/r6h8KiA9pa。
英文:
This just creates a pointer to a Burper (which is an interface). As there is (almost) no sensible use for a pointer to an interface this is valid Go, harmless and useless in practice.
b
is a pointer and points to the zero value of Burper which is nil.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论