我正在研究一個學術問題,并且 Go 出現了恐慌。該代碼將找到字符串的中間字符。func findMiddle(s string) string { len := len(s) half := len / 2 if len == 0 { panic("zero") } if len%2 == 0 { fmt.Println("#53:" + s) str := s[half-1:1] + s[half:1] fmt.Println("Even: " + str) return str } else { fmt.Println("#58: " + s) str := s[half:1] fmt.Println("Odd: " + str) return str }}我的調試輸出如下所示:#58: 1Odd: 1#58: 2Odd: 2#58: 5Odd: 5#53:13Even: 1#53:89Even: 8#58: 233Odd: #53:1597panic: runtime error: slice bounds out of range [2:1]goroutine 1 [running]:main.findMiddle(0xc00001a200, 0x4, 0xc00001a200, 0x4) /home/peter/work/src/misc2/prime-recursion-strings/main.go:68 +0x403main.iterate(0x4f8bc0, 0xc00009c008) /home/peter/work/src/misc2/prime-recursion-strings/main.go:30 +0x92main.main() /home/peter/work/src/misc2/prime-recursion-strings/main.go:17 +0xa3exit status 2正如您所看到的,代碼在發生恐慌之前運行了多次迭代。有任何線索知道發生了什么嗎?在這里測試代碼:https ://play.golang.org/p/_K1DivJST3F
1 回答

動漫人物
TA貢獻1815條經驗 獲得超10個贊
[2:1]
是無效的切片索引。正確的格式是[low:high]
,因此第二個數字必須始終大于(或等于)第一個數字。這就是你感到恐慌的原因。
解決辦法是更換:
str := s[half-1:1] + s[half:1]
和:
str := s[half-1:half] + s[half:half+1]
Playground,可以進一步簡化為:
str := s[half-1:half+1]
- 1 回答
- 0 關注
- 169 瀏覽
添加回答
舉報
0/150
提交
取消