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 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败