Parameters in the Golang struct method need to be defined as pointer types

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The first few days to write a simple counter problem when the page found that the counter is actually always 0, counter does not count, heck ...

The code is as follows:

Type Counter struct {n Int}func (Ctr Counter) servehttp (c http. Responsewriter, req *http. Request) {fmt. fprintf (c, "%08x\n", Ctr) ctr.n++fmt. fprintf (c, "counter =%d\n", CTR.N)}func Main () {http. Handle ("/counter", New (counter)) log. Fatal ("Listenandserve:", http. Listenandserve (":", Nil))}

Research and discover that we

should read


That is, an instance of an object must be defined as the type of the pointer before the correct address can be passed, otherwise the CTR parameter is just a copy of the object.


So the fix code is:


Type Counter struct {n Int}func (Ctr *counter) servehttp (c http. Responsewriter, req *http. Request) {fmt. fprintf (c, "%08x\n", Ctr) ctr.n++fmt. fprintf (c, "counter =%d\n", CTR.N)}func Main () {http. Handle ("/counter", New (counter)) log. Fatal ("Listenandserve:", http. Listenandserve (":", Nil))}

The counter is finally counted ...

Summary: Golang implicitly passes the pointer, but does not implicitly define the pointer, this pit needs the attention of the students.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.