指针 – Golang – &Struct {}与Struct {}之间的差异

前端之家收集整理的这篇文章主要介绍了指针 – Golang – &Struct {}与Struct {}之间的差异前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有理由使用& StructName {}而不是Struct {}来创建结构吗?我看到许多使用前一种语法的例子,即使在 Effective Go Page中,但我真的不明白为什么.

补充说明:
我不确定我是否用这两种方法很好地解释了我的问题,所以让我提炼我的问题.@H_502_3@

我知道通过使用&我会收到一个指针而不是一个值但是我想知道为什么我会使用& StructName {}而不是StructName {}.例如,使用有什么好处:@H_502_3@

  1. func NewJob(command string,logger *log.Logger) *Job {
  2. return &Job{command,logger}
  3. }

代替:@H_502_3@

  1. func NewJob(command string,logger *log.Logger) Job {
  2. return Job{command,logger}
  3. }
好吧,他们会有不同的行为.本质上,如果你想使用结构上的方法修改状态,那么你将需要一个指针,否则一个值就可以了.也许一个例子会更好:
  1. package main
  2. import "fmt"
  3.  
  4.  
  5.  
  6. type test_struct struct {
  7. Message string
  8. }
  9.  
  10. func (t test_struct)Say (){
  11. fmt.Println(t.Message)
  12. }
  13.  
  14. func (t test_struct)Update(m string){
  15. t.Message = m;
  16. }
  17.  
  18. func (t * test_struct) SayP(){
  19. fmt.Println(t.Message)
  20. }
  21.  
  22. func (t* test_struct) UpdateP(m string) {
  23. t.Message = m;
  24. }
  25.  
  26. func main(){
  27. ts := test_struct{}
  28. ts.Message = "test";
  29. ts.Say()
  30. ts.Update("test2")
  31. ts.Say() // will still output test
  32.  
  33. tsp := &test_struct{}
  34. tsp.Message = "test"
  35. tsp.SayP();
  36. tsp.UpdateP("test2")
  37. tsp.SayP() // will output test2
  38.  
  39. }

你可以在go playground运行它@H_502_3@

猜你在找的Go相关文章