Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang, call method from struct

Tags:

methods

go

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

like image 598
nikolai-s Avatar asked Jan 24 '15 19:01

nikolai-s


People also ask

Can a struct have methods Golang?

Structs consist of data, but apart from this, structs also tell about the behavior in the form of methods. Methods attached to structs is very much similar to the definition of normal functions, the only variation is that you need to additionally specify its type.

How do you call a struct function in Golang?

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.

Can we use methods in structure?

'Struct' keyword is used to create a structure. A structure can contain variables, methods, static constructor, parameterized constructor, operators, indexers, events, and property. A structure can not derive/inherit from any structure or class.

Is struct a pointer in Golang?

Access struct using pointer in Golang In the above example, we have used the struct type pointer to access struct members: ptr.name - gives the value of the name member.


1 Answers

You can use a struct literal or a nil pointer.

MyStruct{}.GetSomeAdditionalData()
(*MyStruct)(nil).GetSomeAdditionalData()
like image 131
fuz Avatar answered Nov 03 '22 04:11

fuz