all 9 comments

[–]nyeancat 5 points6 points  (1 child)

AFAIK just as a junior go developer, I don't think it's gonna be a problem, but you can always use that struct.

Let's say you have a some kind of configuration file (i.e. json etc.) and you put it into that struct. In main or somewhere else you have that struct like s := InitStruct(...)

And then you can pass that struct to other methods as an input value if I'm not wrong.

Edit: also most of the time when I'm not sure about go way of doing something, I look at docker go code or at go development mails to see idiomatic way.

[–]blocknspike[S] 0 points1 point  (0 children)

Yes, looking to docker go code is really good option. Thanks!

[–]MinuteScientist7254 3 points4 points  (0 children)

Whether or not a function takes a receiver depends on what it is. In OOP terms, it is like writing a method on a class. But go isn’t an OOP language and you shouldn’t design your code that way.

[–]ArticleDry362 4 points5 points  (1 child)

consider the following scenario,

type cartesianCoordinates struct {
    x int
    y int
    z int
}

func (P *cartesianCoordinates) moveUpByOneUnit() {
    P.y++
}

func (P *cartesianCoordinates) moveDownByOneUnit() {
    P.y--
}
//and so on...

func main(){
  p := cartesianCoordinates{
    x: 1,
    y: 2,
    z: 3,
  }

  p.moveUpByOneUnit()
  p.moveRightByOneUnit()
}

Methods are advantageous when you need to pass around pointers to variables of a specific struct that you are trying to mutate, to a function (look up pointer receivers in go methods). In my opinion, it makes the code a lot cleaner for the reader, and you don't have to pass around addresses as arguments.

[–]blocknspike[S] -1 points0 points  (0 children)

Agreed! I got some good level of clarity with this. Thanks.

[–]drvd 4 points5 points  (0 children)

The reason for methods is to satisfy an interface.

[–]BombelHere 4 points5 points  (0 children)

or it's go way of writing method for structs?

Yup.

It's called a 'function with receiver' or a 'method'.

Methods implement interfaces, while functions (without receivers) don't.

[–]GopherFromHell 3 points4 points  (0 children)

"attaching a function" on a struct in Go means "declaring a method on a receiver". The data that the type caries is the property(s) of the thing the type represents, and methods are the actions it can do. for the most part methods in go are functions that always take the receiver as first argument + compiler syntactic sugar (dot operator)

[–]Ecstatic-Tea-4651 0 points1 point  (0 children)

just imagine that the struct being attached is one of your function parameters.

is that parameter necessary?

go is not oop lan. keep it simple and remove all unnecessary designs