39

I have seen some Go functions defined like this:

type poly struct {
    coeffs [256]uint16
}

func (p *poly) reset() {
    for i := range p.coeffs {
        p.coeffs[i] = 0
    }
}

Which you can later call as:

var p poly
p.reset()

I haven't seen this in other programming languages that I know. What's the purpose of p *poly in the reset function? It seems to be like a function parameter but written before the function name. Any clarification for it?

typos
  • 5,932
  • 13
  • 40
  • 52
  • 5
    Read golang tour https://tour.golang.org/methods/1 will give you an insights to your question. – jeevatkm Aug 11 '17 at 18:53
  • When you understand things, you should also be aware of addressability and how methods are called, which will allow you to understand when a `poly` value can and can't be converted to a `*poly` value; this is important because `poly.reset` requires a `*poly` receiver while you used `p.reset()`, where `p` has type `poly`, not `*poly`. –  Aug 11 '17 at 20:18
  • 17
    The fact that this question was downvoted and closed is a great example for why people hate asking questions on SO. There's nothing wrong with the question, the way it was written or anything of the sort. The linked duplicate answers the question, but there is nothing wrong with this besides that. – mawburn Dec 26 '19 at 03:58
  • It’s a more like a duplicate of https://stackoverflow.com/questions/34031801/function-declaration-syntax-things-in-parenthesis-before-function-name/66607825#66607825 – Michael Freidgeim Mar 12 '21 at 23:15

1 Answers1

37

It means that reset() is a method on *poly.

Machavity
  • 30,841
  • 27
  • 92
  • 100
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • If you look closely, you are modifying the value of the `poly` in the reset function, in such cases, you need to pass the pointer reference not the value to access its actual address. – sibi Jul 21 '20 at 06:13