[英]what does blank do for interface?
Trying to understand the blank functionality of interface
in go. 试图了解go中
interface
的空白功能。
type Manager interface {
GetAge(name string) (int, error)
}
type manager struct {
}
var _ Manager = &manager{}
func NewManager() Manager {
return &manager{}
}
This is a particular idiom used to assert at compile time whether a concrete type implements a given interface. 这是一个特殊的惯用法,用于在编译时断言具体类型是否实现了给定的接口。
In the above code, if the person writing the manager
type forgets to implement a GetAge
method for it, the code won't compile, and the compilation error will tell them exactly which methods are missing. 在上面的代码中,如果编写
manager
类型的人忘了为其实现GetAge
方法,则该代码将无法编译,并且编译错误将准确告知他们缺少哪些方法。
It may appear a bit redundant here, but if the interface required to be implemented by a type has a large number of methods, this technique may be helpful. 在这里看起来可能有点多余,但是如果需要由类型实现的接口具有大量方法,则此技术可能会有所帮助。
Note that because of the above reasons, the code above won't compile. 请注意,由于上述原因,上面的代码将无法编译。 Also, you need to make sure, give that
&manager{}
is used in the blank declaration, that it's *manager
(pointer to manager
) that implements the Manager
interface, and not simply manager
. 另外,您需要确保在空白声明中使用
&manager{}
,它是*manager
(指向manager
指针)实现Manager
接口,而不仅仅是实现manager
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.