Skip to content

Instantly share code, notes, and snippets.

@vvakame
Created October 6, 2016 02:35
Show Gist options
  • Save vvakame/b301db549380036649c8ba00bcb33127 to your computer and use it in GitHub Desktop.
Save vvakame/b301db549380036649c8ba00bcb33127 to your computer and use it in GitHub Desktop.

わからないエラーが出る。

$ go run main.go                                                                                                   1 ↵
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x2167]

goroutine 1 [running]:
panic(0x8ef00, 0xc42000a0c0)
	/usr/local/opt/go/libexec/src/runtime/panic.go:500 +0x1a1
main.main()
	/tmp/main.go:26 +0x127
exit status 2

適当に調べて最適化を切ってみる。

$ go run -gcflags '-N -l' main.go                                                                                  1 ↵
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x2085]

goroutine 1 [running]:
panic(0x8f020, 0xc42000a0c0)
	/usr/local/opt/go/libexec/src/runtime/panic.go:500 +0x1a1
main.(*Sample).Method(0x0)
	/tmp/main.go:13 +0x45
main.main()
	/tmp/main.go:26 +0x7e
exit status 2

わかるエラーになった(わかる

package main
import (
"fmt"
)
type Sample struct {
Foo string
}
func (v *Sample) Method() {
if v == nil {
*v = Sample{}
}
if v.Foo == "" {
v.Foo = "Foo"
}
}
func main() {
var v1 *Sample
v2 := &Sample{
Foo: "Bar",
}
v1.Method()
v2.Method()
fmt.Println(v1)
fmt.Println(v2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment