Go如何将自定义类型切片转换为底层原生类型切片?
Go语言中处理自定义类型切片的
getType函数实现 解决方案代码
package main import ( "fmt" "reflect" ) func getType(arg any) any { ret := arg // 直接返回标准内置类型及其切片 switch ret.(type) { case string, int, int32, int64, []string, []int, []int32, []int64: return ret } rv := reflect.ValueOf(arg) switch rv.Kind() { case reflect.String: ret = rv.String() case reflect.Int, reflect.Int32, reflect.Int64: ret = rv.Int() case reflect.Slice: length := rv.Len() if length == 0 { // 根据切片元素的Kind返回对应原生类型的空切片 elemKind := rv.Type().Elem().Kind() switch elemKind { case reflect.String: ret = []string{} case reflect.Int, reflect.Int32, reflect.Int64: ret = []int64{} } break } // 取第一个元素转换后的类型,用于创建结果切片 firstElem := rv.Index(0).Interface() convertedFirst := getType(firstElem) // 创建同长度的目标类型切片 resultSlice := reflect.MakeSlice(reflect.TypeOf(convertedFirst), length, length) // 遍历所有元素,递归转换后存入结果切片 for i := 0; i < length; i++ { elem := rv.Index(i).Interface() convertedElem := getType(elem) resultSlice.Index(i).Set(reflect.ValueOf(convertedElem)) } ret = resultSlice.Interface() } return ret } // 测试用自定义类型 type customStr string type customInt int32 func main() { // 单个自定义类型测试 myStr := customStr("Hello World") fmt.Printf("单个自定义字符串:Type=%T, Value=%v\n", getType(myStr), getType(myStr)) // 自定义类型切片测试 strSlice := []customStr{"Hello", "World"} convertedStrSlice := getType(strSlice) fmt.Printf("自定义字符串切片:Type=%T, Value=%v\n", convertedStrSlice, convertedStrSlice) // 自定义int类型切片测试 intSlice := []customInt{10, 20, 30} convertedIntSlice := getType(intSlice) fmt.Printf("自定义int切片:Type=%T, Value=%v\n", convertedIntSlice, convertedIntSlice) // 空切片测试 emptyStrSlice := []customStr{} convertedEmptySlice := getType(emptyStrSlice) fmt.Printf("空自定义字符串切片:Type=%T, Value=%v\n", convertedEmptySlice, convertedEmptySlice) }
关键实现说明
- 递归处理元素:对切片的每个元素递归调用
getType,确保自定义类型被转换为对应的原生类型 - 反射创建切片:通过
reflect.MakeSlice根据转换后的元素类型创建原生切片,保证返回值类型符合预期 - 空切片处理:针对空切片,根据元素的Kind直接返回对应原生类型的空切片,避免索引越界问题
运行输出
单个自定义字符串:Type=string, Value=Hello World 自定义字符串切片:Type=[]string, Value=[Hello World] 自定义int切片:Type=[]int64, Value=[10 20 30] 空自定义字符串切片:Type=[]string, Value=[]
内容的提问来源于stack exchange,提问作者user22335954
相关产品推荐
相关产品推荐

