go
compile_error
ai_generated
true
append(s, x) 已求值但未使用
append(s, x) evaluated but not used
ID: go/append-to-slice-without-assignment
95%修复率
90%置信度
1证据数
2023-02-28首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Go 1.20 | active | — | — | — |
| Go 1.21 | active | — | — | — |
| Go 1.22 | active | — | — | — |
根因分析
append() 函数返回一个新切片;忽略返回值会丢弃结果,原始切片保持不变,导致编译时错误。
English
The append() function returns a new slice; ignoring the return value discards the result and the original slice remains unchanged, leading to a compile-time error.
官方文档
https://go.dev/ref/spec#Appending_and_copying_slices解决方案
-
Assign the result of append back to the slice: s = append(s, x). Ensure s is used later in the code.
-
If you want to modify the slice in place, use copy or index assignment instead: s = append(s[:len(s):len(s)], x) to extend capacity.
-
Use a pointer to the slice if you need to modify it inside a function: func foo(s *[]int) { *s = append(*s, x) }
无效尝试
常见但无效的做法:
-
70% 失败
The error 'evaluated but not used' will still occur because s is not used after assignment.
-
90% 失败
The same compile-time error occurs regardless of goroutine; append still returns an unused value.
-
50% 失败
This compiles but discards the result, which is likely a logic bug; the original slice s remains unchanged.