go
type_error
ai_generated
true
cannot use x (variable of type []T) as type []U in append
ID: go/mismatched-types-in-append
82%Fix Rate
85%Confidence
1Evidence
2023-08-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| go1.21 | active | — | — | — |
| go1.22 | active | — | — | — |
| go1.23 | active | — | — | — |
Root Cause
Go's type system enforces strict slice type compatibility; appending a slice of one concrete type to another requires explicit conversion or type assertion even if underlying types are similar.
generic中文
Go 的类型系统强制执行严格的切片类型兼容性;即使底层类型相似,将一个具体类型的切片追加到另一个类型也需要显式转换或类型断言。
Official Documentation
https://go.dev/doc/faq#convert_slice_of_sliceWorkarounds
-
90% success Convert each element individually in a loop: for _, v := range x { y = append(y, U(v)) }
Convert each element individually in a loop: for _, v := range x { y = append(y, U(v)) } -
85% success If T and U are identical underlying types, use a simple copy: y = append(y, x...) after converting via unsafe or generics
If T and U are identical underlying types, use a simple copy: y = append(y, x...) after converting via unsafe or generics
中文步骤
Convert each element individually in a loop: for _, v := range x { y = append(y, U(v)) }If T and U are identical underlying types, use a simple copy: y = append(y, x...) after converting via unsafe or generics
Dead Ends
Common approaches that don't work:
-
Attempting to use a direct type assertion like x.([]U)
95% fail
Type assertion only works for interfaces, not for concrete slice types; it will cause a compile error.
-
Using reflect to convert slices at runtime
85% fail
Reflection is slow and error-prone for slice conversion; it doesn't solve the compile-time type mismatch.
-
Ignoring the error and forcing the append with unsafe.Pointer
99% fail
Using unsafe bypasses type safety, leading to potential memory corruption or undefined behavior.