41

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?

4
  • 5
    Read golang tour tour.golang.org/methods/1 will give you an insights to your question. Commented Aug 11, 2017 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. Commented Aug 11, 2017 at 20:18
  • 18
    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. Commented Dec 26, 2019 at 3:58
  • It’s a more like a duplicate of stackoverflow.com/questions/34031801/… Commented Mar 12, 2021 at 23:15

1 Answer 1

41

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.