接口的方法

huangapple go评论97阅读模式
英文:

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接口,该接口有两个方法getKeygetData。然后,location结构体嵌入了reader接口,并添加了fileLocationerr字段。接下来,location结构体实现了getKeygetData方法。最后,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.

huangapple
  • 本文由 发表于 2010年5月16日 05:58:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/2841901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定