Difference between &Struct{} vs Struct{}

Assuming you know the general difference between a pointer and a value:

The first way allocates a struct and assigns a pointer to that allocated struct to the variable p1.

p1 := &StructName{}

The second way allocates a struct and assigns a value (the struct itself) to the variable s. Then a pointer to that struct may be assigned to another variable (p2 in the following example).

s := StructName{}
p2 := &s

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