Search code examples
gomethods

How to call method from struct without variable


Is it possible to call method from struct without variable with this struct type?

//models.go
type MyStruct struct {
  id int
  name string
}

func (s MyStruct) GetSomeAdditionalData() string {
  return "additional data string"
}

//app.go
func main() {
  fmt.Println(models.MyStruct.GetSomeAdditionalData()) // not works

  var variable models.MyStruct
  fmt.Println(variable.GetSomeAdditionalData()) // it worked
}

Or maybe Go have other method to add some data for struct?

Or maybe I select wrong way to do it? :)


Solution

  • You can use a struct literal or a nil pointer.

    MyStruct{}.GetSomeAdditionalData()
    (*MyStruct)(nil).GetSomeAdditionalData()