英文:
Methods of an interface
问题
下面的方式实现了附加到接口的方法是否正确?
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
}
是的,这种方式是正确的。它定义了一个reader
接口,该接口有两个方法getKey
和getData
。然后,location
结构体嵌入了reader
接口,并添加了fileLocation
和err
字段。接下来,location
结构体实现了getKey
和getData
方法。最后,NewReader
函数返回一个指向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
}
答案1
得分: 4
在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 the type location struct
.
See here: http://golang.org/doc/effective_go.html#interfaces_and_types
答案2
得分: 1
你已经基本完成了。一旦你给location的getKey和getData方法提供有效的实现,*location就会实现reader接口。不需要再做任何事情。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论