在 struct panics 的字段上调用 atomic.AddInt64 invalid memory address or nil pointer dereference,但在我们重新排列字段顺序时不会;为什么?
使用这种类型:
type CountHandler struct {
c *RequestContext
count int64
}
并且调用atomic.AddInt64(&countHandler.count, 1)(此时字段c为零)恐慌。但当我们将其重写为:
type CountHandler struct {
count int64
c *RequestContext
}
错误消失。
我想应该是这样,因为 Go 以顺序方式将数据保存在内存中,并且达到一个nil值会破坏这个(字节)序列;但我想知道为什么又是这样,因为指针应该具有固定大小nil或其他值。
这是 Windows 上的 Go x86 1.4.2,完整的错误消息是:
2015/02/23 12:56:44 http: panic serving [::1]:51886: runtime error: invalid memory address or nil pointer dereference
goroutine 5 [running]:
net/http.func·011()
c:/go/src/net/http/server.go:1130 +0xa8
sync/atomic.AddUint64(0x731144, 0x1, 0x0, 0x0, 0x263168)
c:/go/src/sync/atomic/asm_386.s:118 +0xc
main.(*CountHandler).ServeHTTP(0x731140, 0x263180, 0x122f6380, 0x122f62a0)
C:/Workshop/Devox/Workshop-Go/src/geoho/web/app/app.go:62 +0x42
github.com/julienschmidt/httprouter.func·001(0x263180, 0x122f6380, 0x122f62a0, 0x0, 0x0, 0x0)
C:/Workshop/Devox/Workshop-Go/src/github.com/julienschmidt/httprouter/router.go:232 +0x4c
github.com/julienschmidt/httprouter.(*Router).ServeHTTP(0x122d5d20, 0x263180, 0x122f6380, 0x122f62a0)
C:/Workshop/Devox/Workshop-Go/src/github.com/julienschmidt/httprouter/router.go:298 +0x141
net/http.serverHandler.ServeHTTP(0x122d2280, 0x263180, 0x122f6380, 0x122f62a0)
c:/go/src/net/http/server.go:1703 +0x145
net/http.(*conn).serve(0x122e01e0)
c:/go/src/net/http/server.go:1204 +0x9d8
created by net/http.(*Server).Serve
c:/go/src/net/http/server.go:1751 +0x2ce
慕运维8079593
繁星淼淼
相关分类