go compile_error ai_generated true

append(s, x) evaluated but not used

ID: go/append-to-slice-without-assignment

Also available as: JSON · Markdown · 中文
95%Fix Rate
90%Confidence
1Evidence
2023-02-28First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Go 1.20 active
Go 1.21 active
Go 1.22 active

Root Cause

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.

generic

中文

append() 函数返回一个新切片;忽略返回值会丢弃结果,原始切片保持不变,导致编译时错误。

Official Documentation

https://go.dev/ref/spec#Appending_and_copying_slices

Workarounds

  1. 95% success Assign the result of append back to the slice: s = append(s, x). Ensure s is used later in the code.
    Assign the result of append back to the slice: s = append(s, x). Ensure s is used later in the code.
  2. 85% success 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.
    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.
  3. 90% success Use a pointer to the slice if you need to modify it inside a function: func foo(s *[]int) { *s = append(*s, x) }
    Use a pointer to the slice if you need to modify it inside a function: func foo(s *[]int) { *s = append(*s, x) }

中文步骤

  1. Assign the result of append back to the slice: s = append(s, x). Ensure s is used later in the code.
  2. 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.
  3. Use a pointer to the slice if you need to modify it inside a function: func foo(s *[]int) { *s = append(*s, x) }

Dead Ends

Common approaches that don't work:

  1. 70% fail

    The error 'evaluated but not used' will still occur because s is not used after assignment.

  2. 90% fail

    The same compile-time error occurs regardless of goroutine; append still returns an unused value.

  3. 50% fail

    This compiles but discards the result, which is likely a logic bug; the original slice s remains unchanged.