doushi9474 2015-11-08 11:42
浏览 63
已采纳

&Struct {}与Struct {}之间的区别

Is there a reason why I should create a struct using &StructName{} instead of Struct{}? I see many examples using the former syntax, even in the Effective Go Page but I really can not understand why.

Additional Notes: I'm not sure whether I explained my problem well with these two approaches so let me refine my question.

I know that by using the & I will recieve a pointer instead of a value however I would like to know why would I use the &StructName{} instead of the StructName{}. For example, is there any benefits of using:

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

instead of:

func NewJob(command string, logger *log.Logger) Job {
    return Job{command, logger}
}
  • 写回答

2条回答 默认 最新

  • douyi2664 2015-11-08 16:43
    关注

    Well, they will have different behavior. Essentially if you want to modify state using a method on a struct, then you will need a pointer, otherwise a value will be fine. Maybe an example will be better:

    package main
    import "fmt"
    
    
    
    type test_struct struct {
      Message string
    }
    
    func (t test_struct)Say (){
       fmt.Println(t.Message)
    }
    
    func (t test_struct)Update(m string){
      t.Message = m; 
    }
    
    func (t * test_struct) SayP(){
       fmt.Println(t.Message)
    }
    
    func (t* test_struct) UpdateP(m string)  {
      t.Message = m;
    }
    
    func main(){
      ts := test_struct{}
      ts.Message = "test";
      ts.Say()
      ts.Update("test2")
      ts.Say() // will still output test
    
      tsp := &test_struct{}
      tsp.Message = "test"
      tsp.SayP();
      tsp.UpdateP("test2")
      tsp.SayP() // will output test2
    
    }
    

    And you can run it here go playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突