package main import ( "fmt" "log" "net/http" "os" "time" ) var Q []string func main() { go func() { time.Sleep(1 * time.Second) for { test() } }() Q = append(Q, "233") Q = append(Q, "233") Q = append(Q, "233") time.Sleep(3 * time.Second) Q = append(Q, "233") Q = append(Q, "233") Q = append(Q, "233") Q = append(Q, "233") Q = append(Q, "233") time.Sleep(3 * time.Second) Q = append(Q, "233") time.Sleep(3 * time.Second) Q = append(Q, "233") http.HandleFunc("/", handle) err := http.ListenAndServe(":8080", nil) if err != nil { log.Println("http port has been used.") os.Exit(-1) } } func handle(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() _ = r.ParseForm() _, _ = fmt.Fprint(w, "hello") } func test() { file := queueOut() if file != "" { log.Println(file) } } func queueOut() string { res := Q[0] if len(Q) == 1 { Q[0] = "" return res } Q = Q[1:] return res } 我觉得我这样写没错啊. 但是运行的时候有几率出现
panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1058fe5] goroutine 19 [running]: fmt.(*buffer).WriteString(...) /opt/local/lib/go/src/fmt/print.go:82 fmt.(*fmt).padString(0xc000114040, 0x0, 0x3) /opt/local/lib/go/src/fmt/format.go:110 +0x9d fmt.(*fmt).fmtS(0xc000114040, 0x0, 0x3) /opt/local/lib/go/src/fmt/format.go:328 +0x61 fmt.(*pp).fmtString(0xc000114000, 0x0, 0x3, 0x76) /opt/local/lib/go/src/fmt/print.go:437 +0x122 fmt.(*pp).printArg(0xc000114000, 0x1247a20, 0xc000010050, 0x76) /opt/local/lib/go/src/fmt/print.go:671 +0x878 fmt.(*pp).doPrintln(0xc000114000, 0xc0000cffa8, 0x1, 0x1) /opt/local/lib/go/src/fmt/print.go:1146 +0xb1 fmt.Sprintln(0xc0000cffa8, 0x1, 0x1, 0x1247a20, 0x1) /opt/local/lib/go/src/fmt/print.go:271 +0x52 log.Println(0xc0000cffa8, 0x1, 0x1) /opt/local/lib/go/src/log/log.go:301 +0x3f main.test() /Users/licsber/go/src/test/main.go:52 +0xd7 main.main.func1() /Users/licsber/go/src/test/main.go:17 +0x2f created by main.main /Users/licsber/go/src/test/main.go:14 +0x39 Process finished with exit code 2 小白表示无法理解 这个问题是几率出现. 每次运行不一定都有
