goang-给type定于方法,用Values和用Pointers的区别

其实effectiv go里面说的很清楚了

 

http://weekly.golang.org/doc/effective_go.html#pointers_vs_values

 

我这里写了个例子,还是不明白的话,我在详细解释下

 

 

package main


import "log"

type PointerMethodInvoke struct{
	Foo string
}

func (this *PointerMethodInvoke) ChangeFoo(foo string){
	this.Foo = foo
	log.Println("change Foo,result is :",this.Foo)
}

type ValueMethodInvoke struct{
	Foo string
}

func (this ValueMethodInvoke) ChangeFoo(foo string){
	this.Foo = foo
	log.Println("change Foo,result is :",this.Foo)
}

func main() {
	pointerMethodInvoke := new(PointerMethodInvoke)
	pointerMethodInvoke.Foo = "foo"
	log.Println(pointerMethodInvoke.Foo)
	pointerMethodInvoke.ChangeFoo("bar")
	log.Println(pointerMethodInvoke.Foo)
	
	valueMethodInvoke := new(ValueMethodInvoke)
	valueMethodInvoke.Foo = "foo"
	log.Println(valueMethodInvoke.Foo)
	valueMethodInvoke.ChangeFoo("bar")
	log.Println(valueMethodInvoke.Foo)
}

 

 

输出:

 

2011/12/16 15:03:48 foo

2011/12/16 15:03:48 change Foo,result is : bar

2011/12/16 15:03:48 bar

2011/12/16 15:03:48 foo

2011/12/16 15:03:48 change Foo,result is : bar

2011/12/16 15:03:48 foo

你可能感兴趣的:(value)