go type_error ai_generated true

无法将类型为 []T 的变量 x 用作类型 []U 进行追加

cannot use x (variable of type []T) as type []U in append

ID: go/mismatched-types-in-append

其他格式: JSON · Markdown 中文 · English
82%修复率
85%置信度
1证据数
2023-08-15首次发现

版本兼容性

版本状态引入弃用备注
go1.21 active
go1.22 active
go1.23 active

根因分析

Go 的类型系统强制执行严格的切片类型兼容性;即使底层类型相似,将一个具体类型的切片追加到另一个类型也需要显式转换或类型断言。

English

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

官方文档

https://go.dev/doc/faq#convert_slice_of_slice

解决方案

  1. Convert each element individually in a loop: for _, v := range x { y = append(y, U(v)) }
  2. If T and U are identical underlying types, use a simple copy: y = append(y, x...) after converting via unsafe or generics

无效尝试

常见但无效的做法:

  1. Attempting to use a direct type assertion like x.([]U) 95% 失败

    Type assertion only works for interfaces, not for concrete slice types; it will cause a compile error.

  2. Using reflect to convert slices at runtime 85% 失败

    Reflection is slow and error-prone for slice conversion; it doesn't solve the compile-time type mismatch.

  3. Ignoring the error and forcing the append with unsafe.Pointer 99% 失败

    Using unsafe bypasses type safety, leading to potential memory corruption or undefined behavior.