Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
}
like image 685
linirod Avatar asked Nov 08 '15 11:11

linirod


1 Answers

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
like image 94
John Avatar answered Oct 23 '22 14:10

John