The difference between & Struct {} and Struct {}

Is there a reason why I should create a structure using &StructName{}instead Struct{}? I see a lot of examples of the use of the former syntax even on the page " Effective the beginning," but I really can not understand why.

Additional notes: I'm not sure if I explained my problem well with these two approaches, so let me clarify my question.

I know that with help &I will get a pointer instead of a value, however I would like to know why I would use &StructName{}instead StructName{}. For example, are there any advantages to using:

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

instead:

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

, . , , , , . , :

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

}

go playground

+6

, :

p1.

p1 := &StructName{}

( ) s. (p2 ).

s := StructName{}
p2 := &s
+4

Source: https://habr.com/ru/post/1614934/


All Articles