Search code examples
pointersstructgoinitializationdifference

Difference between &Struct{} vs 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}
}

Solution

  • 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