将非接口命名为“*er”是否符合惯用语?

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

Is it idiomatic having non-interfaces called like "*er"

问题

《Effective Go》(http://golang.org/doc/effective_go.html#interface-names)中提到:

按照惯例,只有一个方法的接口的命名应该是方法名加上 -er 后缀或类似的修改,以构造一个代理名词:ReaderWriterFormatterCloseNotifier 等等。

bufio.io 包中包含了以下内容:

// Reader 实现了对 io.Reader 对象的缓冲。
type Reader struct {
    buf          []byte
    rd           io.Reader
    r, w         int
    err          error
    lastByte     int
    lastRuneSize int
}

在这种情况下,将结构体命名为 "*er" 的形式是否符合惯例?特别是在这种情况下,它是一个与 io.Reader 同名的 struct,而 io.Reader 是一个接口。

英文:

The "Effective Go" states:

> By convention, one-method interfaces are named by the method name plus
> an -er suffix or similar modification to construct an agent noun:
> Reader, Writer, Formatter, CloseNotifier etc.

bufio.io package contains this:

// Reader implements buffering for an io.Reader object.
type Reader struct {
	buf          []byte
	rd           io.Reader
	r, w         int
	err          error
	lastByte     int
	lastRuneSize int
}

Is it idiomatic having structs named like "*er"? Especially in this case it's a struct with the same name as io.Reader which is an interface.

答案1

得分: 2

如果在《Effective Go》或规范中没有提到,那么这就是一个主观问题,我认为只要有意义就可以。

bufio.Readerbytes.Reader为例,它们的命名方式非常合理。

英文:

If it's not in Effective Go or the specs then it's a matter of opinion really, I'd say it's fine as long as it makes sense.

Using bufio.Reader or bytes.Reader as an example, they make perfect sense to be named that way.

答案2

得分: 2

type bufio.Reader struct 这个注释很重要:

// Reader 实现了对 io.Reader 对象的缓冲。

bufio 包添加了

> 它包装了一个 io.Readerio.Writer 对象,创建了另一个对象(ReaderWriter,它也实现了接口,但提供了缓冲和一些文本 I/O 的帮助。

由于 bufio.Reader 并没有添加任何新的服务,只是以缓冲的方式实现了 io.Reader,因此保持这个名称并只实现函数是有意义的:一个 struct 就足够了。

从用户的角度来看,它是一个 Reader,可以在任何需要 io.Reader 的地方使用。

英文:

The comment type bufio.Reader struct are important:

// Reader implements buffering for an io.Reader object.

The bufio packages adds:

> It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.

Since bufio.Reader isn't there to add any new service, but only to implements an io.Reader in a buffered way, it makes sense to keep the name and just implement the functions: a struct is enough.

For the user's point of view, it is a Reader that he/she can uses wherever an io.Reader is required.

huangapple
  • 本文由 发表于 2014年7月3日 00:15:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/24536157.html
匿名

发表评论

匿名网友

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

确定