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.