Explain this code

Technology CommunityCategory: GolangExplain this code
VietMX Staff asked 3 years ago
Problem

In Go there are various ways to return a struct value or slice thereof. Could you explain the difference?

type MyStruct struct {
    Val int
}

func myfunc() MyStruct {
    return MyStruct{Val: 1}
}

func myfunc() *MyStruct {
    return &MyStruct{}
}

func myfunc(s *MyStruct) {
    s.Val = 1
}

Shortly:

  • the first returns a copy of the struct,
  • the second a pointer to the struct value created within the function,
  • the third expects an existing struct to be passed in and overrides the value.