7

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? :)

1
  • 1
    A struct method acts upon the data contained in that particular struct. If you aren't acting on the data in the struct, then don't assign it to the struct. Commented Jan 24, 2015 at 19:50

3 Answers 3

14

You can use a struct literal or a nil pointer.

MyStruct{}.GetSomeAdditionalData()
(*MyStruct)(nil).GetSomeAdditionalData()
Sign up to request clarification or add additional context in comments.

3 Comments

(*MyStruct)(nil).GetSomeAdditionalData() will panic since the nil pointer can't be dereferenced for the value receiver in the method.
@Niemi True. Though, that only applies if the method operators on a value (as opposed to a pointer).
yes. I just wanted to point it out for future readers since a pointer receiver is not used in the code snippet in the question.
1

To say you can. MyStruct.GetSomeAdditionalData() is called method expression and you must provide first argument of type MyStruct to that call. Argument can be anonymous composite literal MyStruct.GetSomeAdditionalData(MyStruct{}). Here is working example https://play.golang.org/p/Wc_DjqnpLC . But all that looks not very sensible.

1 Comment

It works, Thanks! I'll also try find better variant, how to organize my code.
0

You can define a package function (without any receiver).
It differs from a method, as a method needs a receiver.

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

Which you can call directly, without any instance of the struct MyStruct needed (since you don't need any of MyStruct data anyway):

func main() {
  fmt.Println(models.GetSomeAdditionalData())
  fmt.Println(GetSomeAdditionalData())

(the second form works if you are in the package models already)

2 Comments

I have 7 structs and all methods for them should return string. I thought if I'll have struct methods, code will look better. Are you think 7 separate methods will be better variant? Thanks!
@rtm7777 if those strings aren't related to the struct, it is better to manage them at the package level.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.