-1

EDIT: Please see the attached stack overflow issue. It describes exactly what I am trying to get across and then some :)

With reference to the below code, is it better/standardized/convention to return the address of the variable, or create the variable with an address? I know that either way you are modifying the same structure, but I want to know which way is cleaner? I also would like to know if there are any pros / cons to either way of doing it.

type Thing struct {

}

func getThing() *Thing {
  thing := Thing{}

  // modify thing here

  return &thing //return the address to the thing here
}

OR

type Thing struct {

}  

func getThing() *Thing {
  thing := &Thing{} //create the address to the thing here

  //modify thing here

  return thing
}

OR

type Thing struct {

}  

func getThing() *Thing {
  thing := new(Thing) 

  //modify thing here

  return thing
}
twohyjr
  • 68
  • 8

1 Answers1

0

If you want to modify the struct using the method then &Thing{} is a good option.

Example:


type Thing struct {
    data string
}  

func (t Thing) Update1(data string){
  t.data= data;
}

func (t *Thing) Update2(data string)  {
  t.data= data;
}

func getThing1() *Thing {
  thing := Thing{}
  thing.Update1("test") // don't update the data
  return &thing
}

func getThing2() *Thing {
  thing := &Thing{} 
  thing.Update2("test") // update the data
  return thing
}

func main() {
    now := getThing1()
    fmt.Println(now.data) // it doesn't print anything
    now = getThing2()
    fmt.Println(now.data) // print "test"
}

Eklavya
  • 15,459
  • 4
  • 14
  • 41
  • The downvote is not from me, but your post does not answer the question, at all. – mkopriva Apr 27 '20 at 19:23
  • @mkopriva `I also would like to know if there are any pros / cons to either way of doing it.` I just want to give an answer for this part. I just want to add a pros that all. – Eklavya Apr 27 '20 at 19:26
  • There are most probably no pros and no cons, this is largely a question of personal style and taste with no sanctioned guidelines from no official committee. In other words, this seems like an opinion-based question which makes it off-topic for SO. – mkopriva Apr 27 '20 at 19:33
  • @mkopriva for updating struct using own method call is a pros in my thinking and I expect atleast a comment from downvoter. – Eklavya Apr 27 '20 at 19:43