首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

golang struct构造体方法中的参数需要定义为指针类型

2013-10-13 
golang struct结构体方法中的参数需要定义为指针类型前几日写一个网页的简单计数器问题时发现,计数器居然

golang struct结构体方法中的参数需要定义为指针类型

前几日写一个网页的简单计数器问题时发现,计数器居然永远为0,计数器不计数,见鬼了。。。

代码如下:

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(":80", nil))}

计数器终于计数了。。。

总结:golang隐式传递指针,但是不隐式定义指针,此坑需同学们注意。

热点排行