Skip to content

Instantly share code, notes, and snippets.

@tony612
Last active December 6, 2024 08:14
Show Gist options
  • Save tony612/e9d4b5d66fb894efdcc7200c47e8cb60 to your computer and use it in GitHub Desktop.
Save tony612/e9d4b5d66fb894efdcc7200c47e8cb60 to your computer and use it in GitHub Desktop.
go_string_panic
// panic: s should not be WHAT
// goroutine 1 [running]:
// main.main()
// main.go:44 +0x19c
// exit status 2
// panic: runtime error: invalid memory address or nil pointer dereference
// [signal SIGSEGV: segmentation violation code=0x2 addr=0x7 pc=0x102fa19a4]
// goroutine 1 [running]:
// main.main()
// main.go:48 +0x154
// exit status 2
package main
import (
"fmt"
"time"
)
const (
STR1 = "WHAT THE"
STR2 = "HELL"
STR3 = ""
)
type A struct {
s string
}
func main() {
a := A{
s: STR1,
}
go func() {
i := 0
fmt.Printf("len=%d %p\n", len(a.s), &a.s)
for {
switch i % 3 {
case 0:
a.s = STR1
case 1:
a.s = STR2
case 2:
a.s = STR3
}
time.Sleep(1)
i++
}
}()
count := 0
for {
s := a.str()
if count == 0 {
fmt.Printf("len=%d %p\n", len(s), &s)
}
if s == "WHAT" {
panic("s should not be WHAT")
}
if len(s) > 0 {
if s[len(s)-1] == 'E' {
// fmt.Println(s)
count++
}
}
time.Sleep(1)
}
fmt.Println(count)
}
func (a *A) str() string {
return a.s
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment