接口的方法
实现附加到接口的方法的下一种方法是否正确? (getKey
、getData
)
type reader interface {
getKey(ver uint) string
getData() string
}
type location struct {
reader
fileLocation string
err os.Error
}
func (self *location) getKey(ver uint) string {...}
func (self *location) getData() string {...}
func NewReader(fileLocation string) *location {
_location := new(location)
_location.fileLocation = fileLocation
return _location
}
Would be correct the next way to implement the methods attached to an interface? (getKey
, getData
)
type reader interface {
getKey(ver uint) string
getData() string
}
type location struct {
reader
fileLocation string
err os.Error
}
func (self *location) getKey(ver uint) string {...}
func (self *location) getData() string {...}
func NewReader(fileLocation string) *location {
_location := new(location)
_location.fileLocation = fileLocation
return _location
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Go 中,您不需要明确地说您正在实现一个接口 - 如果一个类型具有接口所需的一切,则可以通过该接口使用它。因此,您不需要在
type location struct
中说出reader
。请参阅此处:http://golang.org/doc/ effective_go.html#interfaces_and_types
In Go you don't need to explicitly say that you are implementing an interface—if a type has everything required by an interface, it can be used via that interface. So you don't need to say
reader
inside thetype location struct
.See here: http://golang.org/doc/effective_go.html#interfaces_and_types
你基本上已经做到了。一旦您为 location 的 getKey 和 getData 方法提供有效主体,*location 将实现读取器接口。无需再做任何事情。
You've basically done it already. As soon as you give location's getKey and getData methods valid bodies, *location will implement the reader interface. There's no need to do anything more.