当我命名一个函数为set的方法时,我发现我的代码中至少出现了三个世界setSth
,updateSth
和updateSth
/更新 this
对象的状态。
我对这个选择感到困惑。
我搜索了golang项目的源代码,发现有很多使用setSth
的项目。
0 个项目使用“changeSth”
8 个项目使用“updateSth”
text/tabwriter/tabwriter.go 380:func (b *Writer) updateWidth() { go/ast/commentmap.go 246:func (cmap CommentMap) Update(old, new Node) Node { container/heap/example_pq_test.go 54:func (pq *PriorityQueue) update(item *Item, value string, priority int) { expvar/expvar.go 129:func (v *Map) updateKeys() { encoding/gob/encode.go 101:func (state *encoderState) update(instr *encInstr) { crypto/cipher/gcm.go 236:func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) { 247:func (g *gcm) update(y *gcmFieldElement, data []byte) { index/suffixarray/qsufsort.go 145:func (x *suffixSortable) updateGroups(offset int) {
214 个项目使用“setSth”
net/fd_plan9.go:214:func (fd *netFD) setReadDeadline(t time.Time)
error { net/fd_plan9.go:218:func (fd *netFD) setWriteDeadline(t
time.Time) error { mime/multipart/writer.go:43:func (w *Writer)
SetBoundary(boundary string) error { log/log.go:218:func (l *Logger)
SetFlags(flag int) { log/log.go:232:func (l *Logger) SetPrefix(prefix
string) { bufio/scan.go:198:func (s *Scanner) setErr(err error) {
archive/zip/struct.go:185:func (h *FileHeader) SetModTime(t time.Time)
{ archive/zip/struct.go:223:func (h *FileHeader) SetMode(mode
os.FileMode) { expvar/expvar.go:60:func (v *Int) Set(value int64) {
expvar/expvar.go:86:func (v *Float) Set(value float64) {
expvar/expvar.go:147:func (v *Map) Set(key string, av Var) {
expvar/expvar.go:228:func (v *String) Set(value string) {
testing/benchmark.go:97:func (b *B) SetBytes(n int64) { b.bytes = n }
testing/benchmark.go:430:func (b *B) SetParallelism(p int) {
image/image.go:92:func (p *RGBA) Set(x, y int, c color.Color) {
image/image.go:104:func (p *RGBA) SetRGBA(x, y int, c color.RGBA) {
image/image.go:196:func (p *RGBA64) Set(x, y int, c color.Color) {
最佳答案
关键仍然是一致性:
- 当您开始在包中使用“
UpdateXXX()
”时,请坚持下去。 - 如果您使用
SetXXX()
,也会发生同样的情况。
话虽如此,Get
和 Set
在 Go 中并不是惯用的。当然not for a Getter ,而如果需要的话,setter 函数可能会被调用 SetXXX()
,如“how to set and get fields in golang structs? ”。
另一方面,Update()
可能有特定的目的。
注意:您在 go 源代码中找到的“update()
”方法均未导出(公共(public))。
关于go - 命名成员方法时如何在 "updateSomething"和 "setSomething"之间进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26482781/