golang, methods on values or pointers?

u013834131 · · 1113 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
package main

import "fmt"

type t struct {
	s string
}

func (o t) f1() {
	o.s = "f1"
}

func (p *t) f2() {
	p.s = "f2"
}

func main() {
	t1 := t{
		s: "t1",
	}
	fmt.Println("t1:", t1.s)
	t1.f1()
	fmt.Println("t1:", t1.s)
	t2 := t{
		s: "t2",
	}
	fmt.Println("t2:", t2.s)
	t2.f2()
	fmt.Println("t2:", t2.s)
}
// t1: t1
// t1: t1
// t2: t2
// t2: f2

http://golang.org/doc/faq#methods_on_values_or_pointers (官方FAQ)

Should I define methods on values or pointers?

func (s *MyStruct) pointerMethod() { } // method on pointer
func (s MyStruct)  valueMethod()   { } // method on value

For programmers unaccustomed to pointers, the distinction between these two examples can be confusing, but the situation is actually very simple. When defining a method on a type, the receiver (s in the above examples) behaves exactly as if it were an argument to the method. Whether to define the receiver as a value or as a pointer is the same question, then, as whether a function argument should be a value or a pointer. There are several considerations.

First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer. (Slices and maps act as references, so their story is a little more subtle, but for instance to change the length of a slice in a method the receiver must still be a pointer.) In the examples above, if pointerMethod modifies the fields of s, the caller will see those changes, but valueMethod is called with a copy of the caller's argument (that's the definition of passing a value), so changes it makes will be invisible to the caller.

By the way, pointer receivers are identical to the situation in Java, although in Java the pointers are hidden under the covers; it's Go's value receivers that are unusual.

Second is the consideration of efficiency. If the receiver is large, a big struct for instance, it will be much cheaper to use a pointer receiver.

Next is consistency. If some of the methods of the type must have pointer receivers, the rest should too, so the method set is consistent regardless of how the type is used. See the section on method sets for details.

For types such as basic types, slices, and small structs, a value receiver is very cheap so unless the semantics of the method requires a pointer, a value receiver is efficient and clear.


本文来自:CSDN博客

感谢作者:u013834131

查看原文:golang, methods on values or pointers?

1113 次点击  ∙  1 赞  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传